Updated on: Sat May 20 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
Estimated reading time : 10 min read
c#
.net core
C#
Table of Content
Introduction
-
History of C#
- C# was launch to the public on the year 2000
- It is a programming language based from C++, Java, Pascal
- Microsoft was the company that develop this language
- .Net framework was the first development environment that was created using as foundation C#
- It is Multiparadigm - Can support
- Structural programming
- Imperative
- OOP
- Event Driven
- Functional
Official repo
.NET Core
-
Features
Framework created by Microsoft, for web development, desktop and mobile. Uses C#, F#, VB.
- It is free.
- Cloud Oriented.
- Open Source.
- Multiplatform.
- Has the Support from Microsoft and the development community.
- Its Performance Oriented.
Official Repo
-
Some CLI commands
# It will show all Command's Information dotnet # Shows tha installation path of its components dotnet --info # All existing commands dotnet --help # Check the version dotnet --version # Adds a project to the current that its been working on dotnet add # Same as Build option from Visual Studio IDE dotnet build # Same as Clean option from Visual Studio IDE dotnet clean # Creates a Dotnet project, you can choose from all the variaty that exists dotnet new dotnet nuget dotnet pack dotnet publish dotnet remove # Restore all nuggets packages dotnet restore # Compiles the application dotnet run # Runs the tests dotnet test -
.NET 5
A look into .NET 5
Language functionalities
-
Concatenation
-
- Operator
"Mi nombre tiene" + letras + "letras"- String format
string.Format("Mi nombre tiene {0} letras", letras)- String interpolation
var letras; string res = $"Mi nombre tiene {letras} letras"; -
-
Comments
// Inline Comment /* Multiple lines comment */ /// <summary> /// Inline documentation /// </summary> -
Region
Way to group coding lines, it disappears on compilation time, when publishing the code all lines will be maintained.
#region variables //Related Code Lines #endregion
Variables
-
Types
Some of the essential types that exist are:
-
string
-
Numerics (with its variations)
- sbyte
- byte
- short (or Int16)
- int
- uint
- long
- ulong
- float
- double
- decimal
-
bool
-
Enums
//Enums class Example { //... var gender = Gender.Fem; } enum Gender { Masc = 1, Fem = 2, Other = 0 } -
Nullable
//Nullables DateTime? endDate = null; Console.WriteLine(endDate.Value); //Error Null Exception if value is null Console.WriteLine(endDate?.Date); //Will not produce any errors -
Date
//DateTime DateTime birthDate = new DateTime(1994, 9, 15); DateTime currentDate = DateTime.Now; Console.WriteLine(birthDate.Date.ToString("MM/dd/yy")); int age = birthDate - currentDate; age = age.Days / 360;
-
-
Constants
Constants cannot be modified.
const string name = "Elton";
Loops and conditionals
-
if else
class test { if(conditional > condition) { // Will execute if the condition declared inside the "If" its true } else { // Will execute if the condition declared inside the "If" its false } } -
and, or & not operators
- And ⇒ Allows the addition of another condition, the If statement will be TRUE if BOTH conditions are fullfilled
- Or ⇒ Allows the addition of another condition, the If statement will be TRUE if ANY condition is fullfilled
- Not ⇒ Will switch the result of the If statement to the opposite
// And Operator (&&) if(conditional > condition1 && condition2) // Or Operator (||) if(conditional > condition1 || condition2) // Not Operator (!) if(!condition2) -
else if
Else if is a conditional that will execute after the if and before else, and will have another conditional that will be evaluated
if(Conditional) // Code that will be executed if the Conditional is true else if(Conditional2) { // Code that will be executed if the Conditional is false and Conditional2 is true } else // Code that will be executed if both Conditionals are false -
ternary operator
Its another option to the If statement, it uses the following character (?)
string message = int.TryParse(total, out int contador) ? "Number is valid" : "Number is not valid"; -
for
Possess parameters that indicates how many times should the code execute inside the cycle:
- 1° Iterative Variable initialization, this will be in charge of obtaining the current iterative
- End condition, while its TRUE the cycle will continue
- Iterative variable change reason (can be incremented or decremented) this will help for the iterative value to accomplish the end condition
for(int i=0; i<=5; i++) { //will execute 5 times } -
while
Haves one condition, while the condition its TRUE the execution will keep. Inside this cycle it should be an operation that will allow the condition to pass to FALSE.
while(condition) { // code } -
foreach
Goes through a collection, you can use any property or index of the collection inside this iterator
foreach(var item in new[] {5,4,3,2,1,0}) { //Code }
Basic exception handling
-
try and catch
Use try-catch for exception handling, if the code inside the try statement fails, then it will pass to the catch, here you need to do the exception handling.
int number = 0; try { number = int.Parse(number2string); } catch (Exception ex) { #if DEBUG Console.WriteLine($"An error has occurred {ex.Message}"); Console.WriteLine($"{ex.StackTrace}"); #endif }Multiple catch declarations can exist, according the type of error that will be handled.
Some structures
-
Arrays
Needs brackets, also you must specify the cuatity of values that will be contained here.
int[] name = new int[5]; //Value asignation name[0] = 1; //Variable initialization int[] name2 = new int[5] {1, 2, 3, 4, 5}; -
Dictionaries
Type of collection that has a Pair of Value and Key, the keys are unique.
//Declaration var collection = Dictionary<string, int>(); collection.Add(Guid.NewGuid().ToString(), int.Parse(Console.ReadLine())) //Initialization var collection = Dictionary<string, int>() { {"some value", 1}, {"other example", 1000} }; -
Lists
The difference between arrays and lists, is that the second can be used without declare the cuantity of values it will contain
var test = List<short>(); test.Add(50); test.Add(100); //Initilization var test = List<short>() { 1, 2, 4, 50, 100 };
OOP Basics
For more information please take a look at the folowing:
-
Fundamentals
- Programming paradigm
- Abstraction
- Foundation are classes
- Some languages that support this paradigm C#, Java, C++, Ruby
Concepts
- Classes
- Methods
- Properties
- Inheritance
- Encapsulamiento
- Polymorphism
-
Constructor
Allows to initialize class and set some properties when the class is being instantiated.
public class Test { public string testString; public Test(string args) { testString = args; } } // Instanciacion de la clase Test public class Program { static void Main(string[] args) { var test = new Test("This is a test"); Console.WriteLine($"Instanciating : {test.testString}") } } -
Properties
Allows to expose attributes of a determine class
public class User { public string? Name { get; set; } public string Email { get; set; } public Guid Password { get; private set => "P4ssw0rd"; } }In this special case Password property’s value cannot be changed.
-
Methods
Specific functionalities of a class, to achieve that they use logic.
public class User { public string? Name { get; set; } public string Email { get; set; } public Guid Password { get; private set => "P4ssw0rd"; } public bool IsValid() // Method { return !(string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(Email)); } } -
Inheritance
Allows to utilize methods and properties in multiple classes, each class that inherits from another has the ability to extend the functionality of its parent.
public class Parent { public string Name { get; set; } public int Age { get; set; } public enum Gender {get; set;} } public class Child : Parent // (:) Child inherits Parent { public bool HasToys { get; set; } }
Abstraction
-
Interfaces
Are signatures that allows define properties and methods that are going to be implemented from classes that use these signatures.
- Avoids components coupling
- Allows the implementation of patterns
- Allows the code reusability
- Garanties a implementation standard
public interface IStore { string Name { get; set; } string Direction { get; set; } } -
Abstract type
Abstraction
Mechanism that considerate specific common assets of a complex scenario, ignoring the rest of the data which is, in most cases, unnecessary.
Abstract type
ATD (Abstract Type Data) is a model that defines values and operations that can be performed over them.
It is abstract for the person that uses it, it is not necessary show the intern implementation or details related to this.
//Creating Interface public interface ILog { void SaveLog(string action); } //Implementing Interface using System.IO; public LogText : ILog { public void SaveLog(string action) { string logPath = Directory.GetCurrentDirectory() + @"\Log.txt"; streamWriter = new StreamWriter(logPath); streamWriter.WriteLine($"{DateTime.Now} - {action}"); streamWriter.Close(); } } //Using Implementation, inyecting the dependency on the constructor class test { private ILog _log; public test(ILog log) { _log = log; } _log.SaveLog("ILog Interface is working good") }When implementing Interfaces, you can select many of them. This is not the case for Classes, in this case it would be called inheritance and can be done having as the father class just one class.
public class Application: ILogger, IErrorHandler { // Implementation of both interfaces }
Advanced functionalities
Generics
-
Basic examples
Gives us the possibility of having parameters in which the type is not specified but until the class is being instantiated.
public class GenericList<T> { public void Add(T input){} } public class Program { static void Main(string[] args) { var test = new GenericList<string>(); test.Add("Test1"); test.Add("Test2"); } }Using Generics alongside Inheritance
public class Parent { public string Name { get; set; } public int Age { get; set; } public enum Gender {get; set;} } public class Child : Parent // (:) Child inherits Parent { public bool HasToys { get; set; } } public string GetInformation<T>(T parent) { StringBuilder stringBuilder = new StringBuilder(); var parentObject = parent as Parent; // value as type Parent stringBuilder.AppendLine($"Name:{parentObject.Name}"); stringBuilder.AppendLine($"Age:{parentObject.Age}"); stringBuilder.AppendLine($"Gender:{parentObject.Gender}"); if(parentObject is Child) { var childObject = parent as Child;// value as type Child // all Child properties and methods can be used here stringBuilder.AppendLine($"HasToys:{childObject.HasToys}"); } return stringBuilder.ToString(); }
Linq
-
Basic explanation
Language Integrated Query
Library that helps to extend the programming language to create Queries and process data of collections in a very easy way
- It’s not a programming language
- It’s not a framework
- It’s not SQL
// Linq example var isFour = from c in strings where c == 4 select c ; // Linq Methods students.Where(p => p.CourseCode == "C001" && p.Age > 18);Other examples
//Concat is a Linq Method that will allow you to merge the data of two types of collections foreach (var item in class1.Concat(class2)) { // logic } //FirstorDefault method from Linq, takes the first coincidence or the default value var test = test.FirstOrDefault(p => p.Item == condition);
- Some Visual Studio tips
- Release mode ⇒ configuration deletes the unnecessary code to compile, also improves performance
- Debug mode ⇒ allows debugging
- Compilation can be configured to use 32bits or 64bits
- You can select the starting application for compilation
- Clean and Build ⇒ options, delete all the configuration files
- Re-build ⇒ cleans all the compiles files and builds them
- Debug add watch ⇒ allows the assignation of a variable to see the changes it suffers through time