Examples of c# code in form of a simple tutorial. Containing:
- Console Output
- Variables
- Declaration
- Arithmetic Operators
- Selection Statements
- Iteration Statements
- Arrays and Lists
- Parsing and Exceptions
- Functions
- Enum
- Classes
- Console Input
- File Read & Write
If you find this project useful you can mark it by leaving a Github Star ⭐
And even with community license, if you want help development, you can make a DONATION: _ or _
⚡
Want to Contact for Development & Consulting: www.codis.tech (Quality Assurance)
Please read CONTRIBUTING for details on code of conduct, and the process for submitting pull requests.
When opening issues do write detailed explanation of the problem or feature with reproducible example.
**Also take a look into others packages:
Open source (MIT or cFOSS) authored .Net libraries (@Infopedia.io personal blog post)
| № | .Net library | Description |
|---|---|---|
| 1 | EFCore.BulkExtensions | EF Core Bulk CRUD Ops (Flagship Lib) |
| 2 | EFCore.UtilExtensions | EF Core Custom Annotations and AuditInfo |
| 3 | EFCore.FluentApiToAnnotation | Converting FluentApi configuration to Annotations |
| 4 | FixedWidthParserWriter | Reading & Writing fixed-width/flat data files |
| 5 | CsCodeGenerator | C# code generation based on Classes and elements |
| 6* | CsCodeExample | Examples of C# code in form of a simple tutorial |
Local variables - nonCapitalLetter, camelCase.
Class, Function (Method - in a class) and Property name - CapitalLetter, PascalCase.
DO choose easy readable identifier (eg. HorizontalAlignment more English-readable than AlignmentHorizontal).
DO favor readability over brevity (property CanScrollHorizontally better than ScrollableX (obscure X-axis ref).
DO NOT use underscores (Hungarian notation), hyphens, or any other nonalphanumeric characters.
AVOID using identifiers that conflict with keywords of widely used programming languages.
DRY - Don't Repeat Yourself
YAGNI - You Aren't Gonna Need It (but have as much as you can out of the box)
KISS - Keep it Simple, Stupid - Kelly Johnson
"Good design is as little design as possible." - Dieter Rams
"Everything should be made as simple as possible, but not simpler." - Albert Einstein
"Complexity is your enemy. Any fool can make something complicated. It's hard to keep things simple."-Richard Branson
"Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple." - Steve Jobs
"I have made this letter longer than usual, only because I have not had the time to make it shorter." - Blaise Pascal
"I have just three things to teach: simplicity, patience, compassion. These three are your greatest treasures." - Lao Tzu
LoD - Law of Demeter or principle of least knowledge
SoC - Separation of Concerns; Layers: presentation, business(service), DAL - data access layer, DB - database
DDD - Domain Driven Design
_ RP - Repository Pattern msdn/TheRepoPattern (allows dependency injection and unit test for EF)
_ DI - Dependecy Injection (IoC - Inversion of Control), loosely-coupled
PRG pattern - Post/Redirect/Get
GRASP - General Responsibility Assignment Software Patterns
OOP - Object Oriented Programming
SOLID (object-oriented design) SolidInPictures:
[S] SRP - Single Responsibility Principle (a class should have only a single responsibility)
[O] OCP - Open/Closed Principle (entities[class, function,..] to be open for extension, closed for modification)
[L] LSP - Liskov Substitution Principle (objects replaceable with subtypes instances without altering correctness)
[I] ISP - Interface Segregation Principle (many client-specific interfaces are better than one general-purpose interface)
[D] DIP - Dependency Inversion Principle (Depend upon abstractions, not upon concretions, Dependency injection)
CODE:
// - LINE COMMENT/*SEGMENT COMMENT*/// break point(F5, F10), refactor, search and replace, Go to def., Find all ref., (un)comment
#region MyRegion
// your collapsible code here
#endregion
#region Output
Console.Write("OUTPUT:");Console.WriteLine("Program is running.");Console.WriteLine();
#endregion
#region Variables
// VARIABLES (local - must be assigned)// primitive(built in) type / object (value range)/*bool / Boolean (true, false) [default: false]byte / Int8 (+- 127) [default: 0]short / Int16 (+- 32,767) [default: 0]int / Int32 (+- 2,147,483,647) [default: 0]long / Int64 (+- 9,223,372,036,854,775,807) [default: 0]float (+- 1.5 E−45 to +- 3.40282347 E+38) [default: 0] Precision: ~6-9 digitsdouble (+- 5.0 E−324 to +- 1.7976931348623157 E+308) [default: 0] Precision: ~15-17 digitsdecimal / Decimal (+- 1.0 E-28 to +- 7.9228 E28) [default: 0] Precision: 28-29 digitschar / Char [default: '']string / String [default: null, nullable]var // can be any type*/
#endregion
#region Naming Conventions
/*local variables - nonCapitalLetter, camelCaseClass, Function(Method - in a class) and Property name - CapitalLetter, PascalCaseDO choose easily readable identifier names(exmample HorizontalAlignment more English-readable than AlignmentHorizontal)DO favor readability over brevity.The property name CanScrollHorizontally is better than ScrollableX (an obscure reference to the X-axis).DO NOT use underscores(Hungarian notation), hyphens, or any other nonalphanumeric characters.AVOID using identifiers that conflict with keywords of widely used programming languages.*/
#endregion
#region Declaration
// Declaration of variable (camelCase Notation)boolisAdmin;intcounter;doublesum;decimalnumber;charcharacter;stringname;// Assignment of variableisAdmin=true;counter=5;sum=3.14;number=18.65m;character='a';name="Ben Benito";Console.WriteLine("c"+counter);// Declaration and AssignmentboolisActive=true;// Nullable (can take all values of its underlying value type and an additional null value)bool?isEnded=null;stringcity=null;// String is null (and therefore nullable) by default, so there's no need for this notation)// CastintinputAmount=126;decimalsecondAmount=inputAmount;// implicit castintthirdAmount=(int)secondAmount;// explicit caststringstrNum="1234";intoutputNum=int.Parse(strNum);Console.WriteLine("DECLARATION");Console.WriteLine("T or F: "+isAdmin);Console.WriteLine("Counter: "+counter);Console.WriteLine("Sum: "+sum);Console.WriteLine("Number: "+number);Console.WriteLine("Letter: "+character);Console.WriteLine("Word or Sentance: "+name);Console.WriteLine("Active: "+isActive);Console.WriteLine("Finished: "+isEnded);// string interpolationConsole.WriteLine("City Name: "+city);// Old way to concatenate stringsConsole.WriteLine("City Name: {0}",city);Console.WriteLine($"City Name: {city}");// Newest way, from C# 6 versionConsole.WriteLine();
#endregion
#region Operators
// Arithmetic Operators// = + - * / %intx=10,y=6;// Declaration and assignment of multiple variables of the same type at onceintresult=x+y;Console.WriteLine("OPERATORS");Console.WriteLine("a + b = "+x+" + "+y+" = "+result);Console.WriteLine("a + b = {0} + {1} = {2}",x,y,result);Console.WriteLine($"a + b = {x} + {y} = {result}");x*=2;//x = x * 2;x++;//x = x + 1;//x--;//x = x - 1;Console.WriteLine("x = x * 2 + 1 = "+x);Console.WriteLine("r = x++ = "+x++);// output is the value of x BEFORE incrementingConsole.WriteLine("x= "+x);Console.WriteLine("r = ++x = "+++x);// output is the value of x AFTER incrementingConsole.WriteLine("x = "+x);Console.WriteLine("");// Relation Operators// == != > >= < <=// Logical Operators// && AND// || OR// ! NOT
#endregion
#region Selection Statements (Conditionals)
Console.WriteLine("SELECTION STATEMENTS (Conditionals)");// if, else, switch, caseboolprint=true;if(print)Console.WriteLine("true - ");print=false;if(print)Console.WriteLine("false - no output");if(!print)Console.WriteLine("not false = true - output");intage=20;if(age>18)Console.WriteLine("Adult");elseConsole.WriteLine("Minor");intvalue=23;// value range 0-29stringclause="Value is from-to: ";if(value>=0&&value<10)Console.WriteLine(clause+"0-9");elseif(value>=10&&value<20)Console.WriteLine(clause+"10-19");elseif(value>=20&&value<30)Console.WriteLine(clause+"20-29");elseConsole.WriteLine(clause+"30+");intmod=value%3;if(mod==1)Console.WriteLine("Remainder 1");elseif(mod==2)Console.WriteLine("Remainder 2");elseConsole.WriteLine("Divisible with 3");switch(mod){case1:Console.WriteLine("Remainder 1");break;case2:Console.WriteLine("Remainder 2");break;default:Console.WriteLine("Divisible with 3");break;}int?year=null;// null coalescing operator (??) - returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its resultConsole.WriteLine("Year = "+(year??2017));// returns 2017, as year == nullstringyearType=year%2==0?"Even year":"Odd year";// (? :) - conditional operator, ternary// General case: result = condition ? result if condition is true : result if condition is false;Console.WriteLine("Year type :"+yearType);
#endregion
#region Iteration Statements
Console.WriteLine("ITERATION STATEMENTS");// for, while, do, foreach, in// Jump statements// break, continue, default, return, (go to)// Exception handling statements// throw, try-catchConsole.Write("For loop: ");for(inti=1;i<=5;i++)Console.Write(i+" ");Console.WriteLine("");Console.Write("While a): ");// Do - while loop, executes at least once, even if the condition is not fulfilledintk=40;do{k=k*2;Console.Write(k+" ");}while(k<20);Console.WriteLine("");Console.Write("While b): ");k=1;while(k<20){k=k*2;if(k==8)break;Console.Write(k+" ");}Console.WriteLine("");Console.Write("While c): ");k=1;while(k<20){k=k*2;if(k==8)continue;Console.Write(k+" ");}Console.Write("\n\n");
#endregion
#region Arrays
Console.WriteLine("ARRAYS");double[]fiveDayPrices=newdouble[5];// fixed size;fiveDayPrices[0]=3.45;fiveDayPrices[1]=3.55;fiveDayPrices[2]=3.58;fiveDayPrices[3]=3.30;fiveDayPrices[4]=3.32;Console.Write("Five day prices: ");for(inti=0;i<5;i++){Console.Write(fiveDayPrices[i]+" ");}Console.Write("\nFive day prices backwards: ");for(inti=fiveDayPrices.Length-1;i>=0;i--){Console.Write(fiveDayPrices[i]+" ");}Console.Write("\nForeach: ");foreach(varelementinfiveDayPrices){Console.Write(element+" ");}Console.WriteLine("");Console.WriteLine("Matrix");// Multidimensional arrays// Two-dimensional array. int[,]matrix=newint[3,3];// fixed size;matrix[0,0]=1;matrix[0,1]=2;matrix[0,2]=3;matrix[1,0]=4;matrix[1,1]=5;matrix[1,2]=6;matrix[2,0]=7;matrix[2,1]=8;matrix[2,2]=9;for(inti=0;i<3;i++)for(intj=0;j<3;j++)Console.Write(matrix[i,j]+" ");Console.WriteLine();int[,]matrixB=newint[3,3];// fixed size;for(inti=0;i<3;i++){for(intj=0;j<3;j++){matrixB[i,j]=(i*3)+j+1;Console.Write(matrixB[i,j]+" ");if((j+1)%3==0)Console.WriteLine("");}}// A similar array with string elements. string[,]array2Db=newstring[3,2]{{"one","two"},{"three","four"},{"five","six"}};// Three-dimensional array. int[,,]array3D=newint[,,]{{{1,2,3},{4,5,6}},{{7,8,9},{10,11,12}}};Console.WriteLine("Dif. Matrix");// Array(Jagged) that can have different row size// This could be clarified!int[][]jaggedArray=newint[3][];for(inti=0;i<3;i++){jaggedArray[i]=newint[(i+1)];for(intj=0;j<(i+1);j++){jaggedArray[i]=newint[(i+1)];jaggedArray[i][j]=(i*3)+j+1;Console.Write(jaggedArray[i][j]+" ");if((j+1)%(i+1)==0)Console.WriteLine("");}}// ListList<string>words=newList<string>{"one","two","three",};words.Add("four");words.Add("five");words.Remove("three");Console.WriteLine("");foreach(varwordinwords)Console.Write(word+" ");Console.WriteLine("\n"+words[1]);Console.WriteLine(words.ElementAt(1));List<char>letters=newList<char>(){'a','b','c'};foreach(varletterinletters){Console.Write(letter+" ");}// DictionaryDictionary<String,int>accounts=newDictionary<String,int>{{"Cash",110},{"Receivable",120},{"Supplies",130},};accounts.Add("Insurance",150);accounts.TryGetValue("Supplies",outintaccount);Console.Write("\nSupplies account: "+account);List<string>sentences=newList<string>{"I am playing","I play","You are going","You go","He is running"};sentences.Remove("He runs");// Lambda expression =>IEnumerable<string>ingEndSentences=sentences.Where(a =>a.EndsWith("ing"));// EndsWith, ContainsList<string>ingEndSentences2=sentences.Where(a =>a.EndsWith("ing")).ToList();// EndsWith, ContainsConsole.WriteLine("\nING:");foreach(varsentenceiningEndSentences2){Console.WriteLine(sentence);}List<string>ingEndSentences3=newList<string>();foreach(varsentenceinsentences){if(sentence.EndsWith("ing")){ingEndSentences3.Add(sentence);}}
#endregion
#region Parsing and Exceptions
Console.WriteLine("\n\nPARSING AND EXCEPTIONS");stringcustomNumStr="324erer";intcustomNum;varvalidNum=int.TryParse(customNumStr,outcustomNum);if(validNum)Console.WriteLine(customNum);elseConsole.WriteLine("Parse Error");try{customNum=Int32.Parse(customNumStr);}catch(Exceptionex){Console.WriteLine("Exception:\n"+ex.StackTrace+"\n");//throw new Exception("Exception on Parsing string to int.");}
#endregion
#region Methods
Console.WriteLine("\nMETHODS (Functions)");// Access Modifiers// public - most accessible// protected - in class where declared and all derived classes// internal - within files in the same assembly// private - only in class where declared// Output: return type(one) - [void = no return], side effects// Input: arguments// keyword static - can be called without object instantiationPrintText("To be printed.");PrintText("End.");decimalnum1=12.3m;decimalnum2=2.5m;intnum3=3;decimalquotient=Divide(num1,num2);// num1, num2 are Arguments - values on function callConsole.WriteLine("{0} / {1} = {2}",num1,num2,quotient);Console.WriteLine("{0} * {1} * {2} = {3}",num1,num2,num3,Multiple(num1,num2,num3));Console.WriteLine("{0} * {1} = {2}",num1,num2,Multiple(num1,num2));Console.WriteLine("{0} * {0} = {1}",num1,Multiple(num1));Console.WriteLine("5! = "+Fact(5));//RecursionConsole.WriteLine("6! = "+Factorial(6));Console.WriteLine("Log10(136) = "+Math.Log10(136));
#endregion
#region Enum
Console.WriteLine("\nENUM");// EnumeratorGenderwordGender=Gender.Neutrum;Genderword2Gender=(Gender)1;// castConsole.WriteLine("word Gender: "+wordGender);Console.WriteLine("word2 Gender: "+word2Gender);if(wordGender==Gender.Neutrum){Console.WriteLine("word Gender: "+wordGender.ToString());Console.WriteLine("word Gender Id: "+(int)wordGender);}SexpersonSex=Sex.Male;Console.WriteLine("Sex: "+personSex.ToString());Console.WriteLine("Sex: "+personSex.GetDescription());Console.WriteLine("All Genders:");foreach(GendergenderinEnum.GetValues(typeof(Gender))){Console.WriteLine("- {0}",gender.GetDescription());}
#endregion
#region Classes
Console.WriteLine("\nCLASSES");decimalxReal=2,xImag=3;decimalyReal=4,yImag=5;decimalzReal,zImag;zReal=Add(xReal,yReal);zImag=Add(xImag,yImag);ComplexNumberxComplex=newComplexNumber(2,3);ComplexNumberyComplex=newComplexNumber(4,5);ComplexNumberzComplex=xComplex.Add(yComplex);// System ClassDateTimecurrentDate=DateTime.Now;Console.WriteLine("DateTime.Now() = {0}",currentDate);Console.WriteLine("Date = {0} ",currentDate.ToString("dd.MM.yyyy"));Console.WriteLine("Date = {0:dd.MM.yyyy} ",currentDate);Console.WriteLine("Year = "+currentDate.Year);// Custom Classes// ComplexNumberConsole.WriteLine("");Console.WriteLine(ComplexNumber.Format);Console.WriteLine(ComplexNumber.GetDescription());ComplexNumbercomplex0=newComplexNumber();complex0.Real=1;ComplexNumbercomplex1=newComplexNumber(5,3);doubler=complex1.Real;ComplexNumbercomplex2=newComplexNumber{Real=6,Imag=7};ComplexNumbercomplex3;complex3=newComplexNumber(){Real=4,Imag=2};MoreComplexNumbercomplex4=newMoreComplexNumber(4,2);MoreComplexNumbercomplex=newMoreComplexNumber();ComplexNumbersummation=complex1.Add(complex2).Add(complex3);//ComplexNumber summation2 = ComplexNumber.Add(ComplexNumber.Add(complex1, complex2), complex3);ComplexNumberdivision=complex1.Divide(complex2);Console.WriteLine("c0 = "+complex0);Console.WriteLine("c1 = "+complex1);Console.WriteLine("c2 = "+complex2.ToString());Console.WriteLine("c3 = "+complex3.ToDiffString());Console.WriteLine("c4 = "+complex4.ToDiffString());Console.WriteLine("\nsummation = "+summation.ToDiffString());Console.WriteLine("division = "+division.ToDiffString());Console.WriteLine("minus = "+newComplexNumber(2,-5).ToDiffString());Console.WriteLine("real = "+newComplexNumber(7,0).ToDiffString());Console.WriteLine("c1(modul) = "+complex1.Modul());Console.WriteLine("c1 ^ 0 ="+complex1.Pow(0));Console.WriteLine("c1 ^ 1 ="+complex1.Pow(1));Console.WriteLine("c1 ^ 2 ="+complex1.Pow(2));Console.WriteLine("c1 ^ 4 ="+complex1.Pow(2));Console.WriteLine("c1 ^ (-2) ="+complex1.Pow(-2));List<ComplexNumber>roots=complex1.Nroot(3);Console.WriteLine("c1 ^ (1/3) = ");foreach(varcinroots)Console.WriteLine(c);// UserUseruser=newUser(){FirstName="John",LastName="Reacher",PersonSex=Sex.Male,BirthDate=DateTime.Parse("12/5/1987"),UserName="Johnny",Email="joe@gmail.com",Company="Google",YearsOfService=5,Sallary=2000/*, HomeAddress = new Address() { City = "Banjaluka", Street = "Jevrejska" }*/};user.ResetPassword("1234abc!");user.HomeAddress=newAddress(){City="London",Street="Baker Street"};Console.WriteLine("\nUSER: "+user);Console.WriteLine("Year of Birth: "+user.BirthDate.Year);Console.WriteLine("City: "+user.HomeAddress.City);SquareSquare=newSquare(4);Console.WriteLine("Square(side:4), area = "+Square.CalcArea());
#endregion
#region InputConsole
Console.WriteLine("INPUT (console)");stringinput=null;while(input!=""){Console.Write("\nInput number:");input=Console.ReadLine();boolinputValid=int.TryParse(input,outintinputNum);if(inputValid)Console.WriteLine("Number is valid. (Press Enter to Finish)\n");elseConsole.WriteLine("Number is not valid.(Press Enter to Finish)\n");}
#endregion
#region InputFile
Console.WriteLine("INPUT (file)");Console.Write("\nInput file path(Enter for no file, 'd' for default[ComplexIn.csv]): ");stringdesktop_path=Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"//";stringfilePath=null;stringinputFilePath=Console.ReadLine();if(inputFilePath=="d")inputFilePath="ComplexIn.csv";if(inputFilePath!="")filePath=desktop_path+inputFilePath;stringoutput_file="ComplexOut.csv";stringline=null;charseparator=',';List<ComplexNumber>complexNumbers=newList<ComplexNumber>();if(inputFilePath!="")using(StreamReaderstr_reader=newStreamReader(filePath)){str_reader.ReadLine();// skips first line as it contains names of columnswhile((line=str_reader.ReadLine())!=null){string[]values=line.Split(separator);complexNumbers.Add(newComplexNumber(Double.Parse(values[0]),Double.Parse(values[1])));}//output all objects to the filestringoutput_path=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);using(StreamWriterwr=newStreamWriter(desktop_path+output_file)){wr.WriteLine("Real,Imag");foreach(varcomplexNumberincomplexNumbers)wr.WriteLine(complexNumber.ToCSV());}}Console.WriteLine("Press Enter for Quit.");Console.ReadKey();// Don't copy code, all that is repeated should be in functions