C# Tutorial For Beginners (2023)

This C# tutorial is for students and beginners who want to learn C# programming. Basic requirement to learn C# is basic understanding of programming and some general concepts of object oriented programming. If you're new to OOP, I recommed learning basics of OOP here, Introduction to Object Oriented Programming.

In this tutorial:

  1. Introduction to C#
  2. Getting Ready
  3. First C# Application
  4. C# Types
  5. Value and Reference Types
  6. C# Structs
  7. C# Enums
  8. C# Class
  9. Class Access Modifiers
  10. C# Field
  11. C# Constructor
  12. C# Property
  13. C# Method
  14. C# Method Overloading
  15. C# Expression
  16. C# Operator
  17. C# Statements
  18. C# if else Statement
  19. C# switch Statement
  20. C# for Statement
  21. C# foreach Statement
  22. C# do while Statement
  23. C# while Statement
  24. C# go to Statement
  25. C# break Statement
  26. C# continue Statement
  27. C# return Statement
  28. C# Interface
  29. C# Partial Class
  30. C# Static Class
  31. C# Abstract Class
  32. C# Array
  33. C# String
  34. C# Dictionary
  35. C# List
  36. Summary

C# Tutorial For Beginners (1)

1. Introduction to C#

C# is a simple, modern, and object-oriented programming language developed by Microsoft. C# is an open source project managed by the .NET Foundation. C# is a fully mature object-oriented programming language and allows developers to build cross-platform applications for Windows, Web, and mobile platforms. C# apps can be deployed on Linux, Windows, iOS, and Android operating systems.

C# is a modern programming language. We can use C# to build today’s modern software applications. C# can be used to develop all kind of applications including Windows client apps, components and libraries, services and APIs, Web applications, Mobile apps, cloud applications, and video games.

Here is a detailed article:What Can C# Do For You

Microsoft supports two software development frameworks, .NET Framework and .NET Core. .NET Framework was launched in 2001 to develop Windows and Web applications. But with the rise of open source trends, Microsoft open sourced language compilers and .NET and the new .NET is called .NET Core. Going forward, there is going to be only one version of .NET, that will be .NET. The next version of .NET is going to be released in 2020, called .NET 5.

Here is a detailed article:The Future of .NET

2. Getting Ready

Before starting your first C# application, you will need an editor or an Integrated Development Environment (IDE), where you can type and compile your code. Visual Studio developed by Microsoft is the best IDE out there for C# developers. The current version of Visual Studio is Visual Studio 2019.

Visual Studio 2019 comes in three different flavors – Visual Studio 2019 Enterprise, Visual Studio 2019 Professional, and Visual Studio 2019 Community.

Visual Studio 2019 Community edition is a free. We’ll use Visual Studio 2017 Community edition.

Alternatively, you may also use Visual Studio Code. Visual Studio Code is a free, lightweight, open source code editor for writing and debugging code. VS Code supports major programming languages.

You may download Visual Studio 2017 Community here.

3. First C# Application

Let’s write our first simple “Hello, World!” program in C#. This is the simplest program you can write in C#. The program will write output on your console saying, “Hello, C# word!”

Open Visual Studio 2019 Community.

Select File > New > Project.

C# Tutorial For Beginners (2)

Select Templates > Visual C# > .NET Core > Console App (.NET Core).

C# Tutorial For Beginners (3)

Now, give your project a name by typing a name in the Name TextBox. I name my project, HelloCSharp.

Click OK button to create the project.

This action creates a console app.

C# Tutorial For Beginners (4)

Double click on Program.cs in Solution Explorer and delete everything in the file.

Now type the following code.

  1. usingSystem;
  2. classHello
  3. {
  4. staticvoidMain()
  5. {
  6. Console.WriteLine("Hello,C#World!");
  7. Console.ReadKey();
  8. }
  9. }

Build and run. Hit Ctrl+F5.

The action compiles and runs your code by creating a HelloCSharp.exe file in your preselected location. The result is “Hello, C# World!” is printed on system console.

As you can see in Figure 5, HelloCSharp.exe is created in C:\Mahesh\Csharp\HelloCSharp\bin\Debug\folder.

Output looks like this,

C# Tutorial For Beginners (5)

Well done!

4. C# Types

C# is a strongly typed language. Types in C# can be divided into two categories – built-in types and custom types.

Built-in types are bool, byte, sbyte, char, decimal, double, float, int, uint, long, ulong, object, short, ushort, and string.

The following code in is example of how to declare variables, assign values to them, and use them.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("TypesSample");
  7. //Declareintvariable
  8. inti=34;
  9. //charvariable
  10. charc='m';
  11. //floatvariable
  12. floatper=6.8f;
  13. //objectvariable
  14. objecto=c;
  15. //stringvarialbe
  16. stringname="MaheshChand";
  17. //Useiinanoperation
  18. intcounter=i+1;
  19. /*Usecinacondition.Checkifthevalueofcis'm'
  20. theprintcandcounter*/
  21. if(c=='m')
  22. {
  23. Console.WriteLine("iis{0}:",i);
  24. Console.WriteLine("counteris{0}:",counter);
  25. Console.WriteLine("cis{0}:",c);
  26. Console.WriteLine("nameis{0}:",name);
  27. Console.WriteLine(counter);
  28. }
  29. Console.ReadKey();
  30. }
  31. }

Learn more here:Introduction To Types In C#

5. Value and Reference Types

C# supports value and reference types.

A value type variable contains the actual data within its own memory allocation. Value types derived from System.ValueType. There are two categories of value types, structs and enum.

A reference type is a reference to a memory location where the actual data is stored. The main reference types are class, array, interface, delegate, and event. A null value is assigned to a reference type by default. A type assigned to a null value means the absence of an instance of that type.

Learn more here:C# Concepts - Value Type And Reference Type

6. C# Structs

A struct type is a value type that is typically used to encapsulate a group of variables that are similar. A struct type can declare constructors, constants, fields, methods, properties, indexers, operators, and nested types.

The following code is an example of use of a struct Book uses a record for a book with four members, Title, Author, Price, and Year. The Main program creates an object of Book struct, set its member values, and print the values.

  1. usingSystem;
  2. namespaceStructSample
  3. {
  4. //Bookstruct
  5. publicstructBook
  6. {
  7. publicstringTitle;
  8. publicstringAuthor;
  9. publicdecimalPrice;
  10. publicshortYear;
  11. }
  12. classProgram
  13. {
  14. staticvoidMain(string[]args)
  15. {
  16. Console.WriteLine("StructSample!");
  17. //CreateaBookobject
  18. BookmyBook=newBook();
  19. myBook.Title="SimplifiedC#";
  20. myBook.Author="MaheshChand";
  21. myBook.Price=45.95M;
  22. myBook.Year=2017;
  23. Console.WriteLine($"Book{myBook.Title}waswrittenby{myBook.Author}"+
  24. $"in{myBook.Year}.Priceis{myBook.Price}");
  25. Console.ReadKey();
  26. }
  27. }
  28. }

Learn more here:Struct In C#

7. C# Enums

Enums in C# are used to represent a set of constants as integral values. For example, to represent a week day, we know there are only seven days in a week.

Here are some common examples of struct types.

(Video) C# Tutorial For Beginners - Learn C# Basics in 1 Hour

  • WeekDay – Mon, Tue, Wed, Thu, Fri, Sat, Sun
  • Months – Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
  • Rectangle – Left, Top, Bottom, Right
  • Point – X, Y

Here are couple of examples of enums.

  1. //Createanenumofweekdays
  2. publicenumWeekDays{Sun,Mon,Tue,Wed,Thu,Fri,Sat};
  3. //CreateanenumofRGBcolors
  4. publicenumRGB{Red,Green,Blue};

Learn more here:Enum In C#

8. C# Class

Classes are the foundation of an object-oriented programming language such as C#. A class is a logical unit of data. Classes have members such as properties, fields, methods, and events.

The following code is a Person class with three private members, name, age, and sex. The class also has three public properties. We will discuss private and public properties shortly.

  1. //Personclass
  2. classPerson
  3. {
  4. //Membersofaclass
  5. privatestringname;
  6. privateInt16age;
  7. privatestringsex;
  8. //Publicpropertiesofaclass
  9. publicstringName
  10. {
  11. get{returnthis.name;}
  12. set{this.name=value;}
  13. }
  14. publicInt16Age
  15. {
  16. get{returnthis.age;}
  17. set{this.age=value;}
  18. }
  19. publicstringSex
  20. {
  21. get{returnthis.sex;}
  22. set{this.sex=value;}
  23. }
  24. }

In C#, keyword new is used to create an instance of a class. The following code snippet sets the values of Name, Age, and Sex properties of object p.

  1. p.Name="MaheshChand";
  2. p.Age=40;
  3. p.Sex="Male";

The following code now reads the values of the members of object p.

  1. //PrintPersondetails
  2. Console.WriteLine("Theperson{0}is{1}yearsold{2}.",p.Name,p.Age,p.Sex);

9. Class Access Modifiers

Access modifiers are accessibility levels of types and type members and set rules how a type and its members can be used within the type, current assembly, and other assemblies.

The following table describes class or struct member accessibility type and their scopes.

Access Modifier

Scope

public

The type or members can be accessed by the code in the same assembly or assemblies that reference it.

private

The type or members can be accessed only by code in the same class.

protected

The type or members can be accessed only by code in the same class, or the classes that are derived from it.

internal

The type or members can be accessed by the code in the same assembly but not from other assemblies.

protected internal

The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly.

private protected

The type of member can be accessed within the same class or the classes derived within the same assembly.

10. C# Field

A field member is a variable of a class or struct. A field can be public, private, protected, internal, or protected internal.

Fields in a class can have different accessibility levels. In the following code, fields name, age, and sex are private fields. That means they can only be accessed within the same class only. Public fields can be accessed from anywhere. Protected fields can be accessed within the Person class and any classes derived from it.

  1. ///Personclass
  2. classPerson
  3. {
  4. //Membersofaclass
  5. privatestringname;
  6. privateInt16age;
  7. privatestringsex;
  8. protectedstringbook;
  9. protectedinternalintcode;
  10. publicInt16Year;
  11. }

A field member can also be read-only. This means the field can only be assigned in the declaration or in the constructor of the class.

If the field is not static, you have to access fields from the class instance. The code snippet in Listing 20 creates an instance of the Person class and sets the value of Year field.

  1. Personp=newPerson();
  2. p.Year=2000;

Listing 20.

A field can also be static. That means, the fields can be available to the code without creating an instance of a class. A static field is declared using the static keyword and a readonly field is declared using the readonly keyword. These both keywords can be combined to declare a readonly static field. The following code snippet declares a readonly static variable.

  1. publicstaticreadonlystringauthor="MaheshChand";

Fields can be variables or constants.

Learn more here:Fields and Properties in C#

11. C# Constructor

Constructors are responsible for creating an instance of a class or struct. Constructors are methods with the same name as a class or struct and must be called to create an instance of a class or struct. The constructor is called using the new operator.

Let’s look at a simple class Person that has four members.

  1. ///Personclass
  2. classPerson
  3. {
  4. //Membersofaclass
  5. privatestringname;
  6. privateintage;
  7. privatestringsex;
  8. privatestringprofession;
  9. }

For example, the following code snippet creates a Person object using the new operator and calls a constructor.

  1. Personp=newPerson();

Once an object is created (p in this case), now it can be used to call other members of ‘p’. For example, the following code snippet sets the value of name of ‘p’.

  1. p.name="MaheshChand";

Constructors are used to initialize the data members of new objects. A class or struct can have one or more than one constructor. A constructor does not have a return type.

Learn more here: Constructors and Its Types in C# With Examples

12. C# Property

Property members of a class provides its callers to access a class’s private field members. Property members expose private fields through special methods called accessor. The get accessor is used to return the property value and the set accessor is used to assign a new value to the property.

Let’s take a look at the following code that declares the Person class with three private fields, name, age, and sex. The private fields are exposed to the external programs through public properties, Name, Age, and Sex.

  1. ///Personclass
  2. classPerson
  3. {
  4. //Membersofaclass
  5. privatestringname;
  6. privateintage;
  7. privatestringsex;
  8. //Constructor
  9. publicPerson()
  10. {
  11. }
  12. //Publicpropertiesofaclass
  13. publicstringName
  14. {
  15. get{returnthis.name;}
  16. set{this.name=value;}
  17. }
  18. publicintAge
  19. {
  20. get{returnthis.age;}
  21. set{this.age=value;}
  22. }
  23. publicstringSex
  24. {
  25. get{returnthis.sex;}
  26. set{this.sex=value;}
  27. }
  28. }

The following code creates a Person class objects and sets its properties. Once the properties are set, the actual values of the properties actually copied inside the object. The following code reads the properties values and prints them on the console.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. //CreateaPersonobject
  7. Personp=newPerson();
  8. //SetPersonproperties
  9. p.Name="MaheshChand";
  10. =40;
  11. p.Sex="Male";
  12. //GetPersonproperties
  13. Console.WriteLine("Person1{0}is{1}yearsold{2}.",p.Name,p.Age,p.Sex);
  14. Console.ReadKey();
  15. }
  16. }

Learn more here: Understanding Properties In C#

13. C# Method

A method member of a class is a block of code that performs a specific task. A method signature is a combination of an access modifier followed by an additional modifier, return type, method name, and method parameters. A typical method signature looks like the following, where a public method returns a bool value and takes two parameters. The method’s code block starts with an open bracket ‘{‘ and ends with a closing bracket ‘}.

  1. //Methodsignature
  2. publicboolMethodName(intparam1,stringparam2)
  3. {
  4. //Implementation
  5. returnfalse;
  6. }

A method can return a void or a data type. Method can also take arguments and also return multiple values.

Let’s add a method, SayHello to our Person class, that prints a message with the person’s name to the console. The method SayHello does not return a value. The final Person class looks like the following.

  1. ///Personclass
  2. classPerson
  3. {
  4. //Membersofaclass
  5. privatestringname;
  6. privateintage;
  7. privatestringsex;
  8. privatestringprofession;
  9. privateboolretired=false;
  10. //Overloadedconstructor
  11. publicPerson(stringpersonName,intpersonAge,stringpersonSex)
  12. {
  13. this.name=personName;
  14. this.age=personAge;
  15. this.sex=personSex;
  16. }
  17. //Publicpropertiesofaclass
  18. publicstringName
  19. {
  20. get{returnthis.name;}
  21. set{this.name=value;}
  22. }
  23. publicintAge
  24. {
  25. get{returnthis.age;}
  26. set{this.age=value;}
  27. }
  28. publicstringSex
  29. {
  30. get{returnthis.sex;}
  31. set{this.sex=value;}
  32. }
  33. ///<summary>
  34. ///Asimplemethodprintsoutamessage
  35. ///</summary>
  36. publicvoidSayHello()
  37. {
  38. if(this.name.Length>0)
  39. Console.WriteLine("Hello{0}fromthePersonclass",this.name);
  40. }
  41. }

Now let’s call this method from our Main method. As you’ve seen earlier in case of properties and fields, we call a method in a similar way we can any other members of a class or struct. The following code creates an instance of Person class, sets its Name property, and calls SayHello method.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. //CreateaPersonobject
  7. Personperson=newPerson("MaheshChand",40,"male");
  8. //CallSayHellomethod
  9. person.SayHello();
  10. Console.ReadKey();
  11. }
  12. }

Often times, a caller program needs to pass some data to a class. The passed data may be used for processing, business logic, and decision making. The last portion of a method signature is a list of method parameters that are passed by the caller program.

(Video) C# Tutorial - Full Course for Beginners

A method defines the type and name of parameters. Multiple parameters are separated by commas.

Here is a method that takes three parameters and returns a value.

  1. publicdecimalCalculateSalary(inthours,decimalrate,decimalbonus)
  2. {
  3. //Payment=numberofhoursworked*rate+bonus
  4. return(hours*rate)+bonus;
  5. }

Now let’s call the CalculateSalary method from our Main method.

  1. //CalculatesalaryofPerson
  2. decimalsalary=person.CalculateSalary(160,50,3000);
  3. Console.WriteLine("{0}getspaid${1}.",person.Name,salary);

14. C# Method Overloading

C# allows you to declare same name methods differentiated by their signature. This process is called method overloading. The following class RateCalculator declares a method CalculateCost with three different signatures.

  1. publicclassRateCalculator
  2. {
  3. privatedecimaltotal;
  4. //Refreturnmethod
  5. publicdecimalCalculateCost(decimalprice,decimalrate)
  6. {
  7. total=price*rate;
  8. returntotal;
  9. }
  10. //Methodwithanoutparameter
  11. publicvoidCalculateCost(decimalprice,decimalrate,outdecimaltotal)
  12. {
  13. total=price*rate;
  14. }
  15. //Methodwithmultiplereturnvalues
  16. publicvoidCalculateCost(decimalprice,decimalrate,outdecimaltotal,outdecimalmin,outdecimalmax)
  17. {
  18. min=rate*0.5m;
  19. max=rate*2;
  20. total=price*rate;
  21. }
  22. }

The call of a method depends on the number and types of arguments passed to the method call. The following code calls these three difference overloaded methods.

  1. //Methodoverloadingsample
  2. usingSystem;
  3. classProgram
  4. {
  5. staticvoidMain(string[]args)
  6. {
  7. RateCalculatorcalculator=newRateCalculator();
  8. decimaltotal=calculator.CalculateCost(12.5m,6.8m);
  9. calculator.CalculateCost(12.5m,6.8m,outdecimalcost);
  10. calculator.CalculateCost(12.5m,6.8m,outdecimaltotalcost,outdecimalminrate,outdecimalmaxrate);
  11. Console.WriteLine("Totalcost{0}",totalcost);
  12. Console.ReadKey();
  13. }
  14. }

Learn more here:Method Overloading In C#

15. C# Expression

An expression is a sequence of operators and operands that specify some sort of computation and the result is evaluated in a single value or object. The following code snippet is an example of two expressions.

  1. Convert.ToInt32("12");
  2. 10+5;

The first expression converts a string “12” to an integer value and the second expression adds two numbers.

Typically, expressions are used in statements. For example, the following code snippet is an example of a statement. The right side of the statement is an expression that adds two numbers.

  1. inta=10+5;

An expression can consist literal values, and method invocations. The following code snippet uses literal names to add in an expression.

  1. stringname="Mahesh"+"Chand";

An expression can also be used in method invocation. A method invocation requires the name of the method, followed by parenthesis and any method parameters. The following code snippet invokes two methods.

  1. Console.WriteLine("OperatorsSample!");
  2. Console.ReadKey();

Learn more here: Expressions 😀and Operators in C#

16. C# Operator

An operator is responsible for an operation. For example, the operators + and - indicate adding and subtracting operands, such as values, objects, and literals. An operand can also be an expression, or any number of sub expressions.

The following code is a simple example of operators and operands.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("OperatorsSample!");
  7. //Declarevariables
  8. inta=10;intb=20;
  9. decimald=22.50m;
  10. stringfirst="Mahesh";stringlast="Chand";
  11. //Use+and-operatorstoaddandsubtractvalues
  12. inttotal=a+b;
  13. decimaldTotal=a+b+d;
  14. intdiff=b-a;
  15. Console.WriteLine("diff:"+diff);
  16. stringname=first+""+last;
  17. Console.WriteLine("Name:"+name);
  18. Console.ReadKey();
  19. }
  20. }

The following line is a code expression. The ‘+’ operator applies to two variables, a and b, and the result is stored in variable total.

  1. inttotal=a+b;

The code also declares other variables of type decimal, and strings. The following code snippet adds a decimal value to two int values.

  1. decimaldTotal=a+b+d;

The following code snippet adds two string values. An extra space is also added during the operation.

  1. stringname=first+""+last;

There are three types of operators, unary, binary, and ternary.

Learn more here: Operators in C#

17. C# Statements

A statement is a part of a program that represents an action such as declaring variables, assigning values, calling methods, loop through a collection, and a code block with brackets. A statement can consist of a single line ends with a semicolon, or a code block enclosed in {} brackets.

The following code snippet has two statements.

  1. decimald=22.50m;
  2. stringfirst="Mahesh";

Here is an if..else statement with several lines of code.

  1. if(d>22)
  2. {
  3. d-=10;
  4. Console.WriteLine("dis{0}",d);
  5. }
  6. else
  7. {
  8. d+=10;
  9. Console.WriteLine("dis{0}",d);
  10. }

18. C# if . . .else Statement

The if . . .else statement is also known as a conditional statement. Here is the syntax of if..else statements.

  1. if(condition)
  2. {
  3. Statement
  4. }
  5. else
  6. {
  7. Statement
  8. }

The if. . .section of the statement or statement block is executed when the condition is true; if it’s false, control goes to the else statement or statement block. The ‘else’ portion of the statement is optional.

The following code uses if statement to check if the value of a is less than 0, then display a message, ‘a is negative’.

  1. inta=-1;
  2. if(a<0)
  3. {
  4. Console.WriteLine("aisnegative.");
  5. }

The following code snippet uses if..else statement to check if the value of a is less than 0. If not, then display a message, ‘a is 0 or positive’.

  1. inta=-1;
  2. if(a<0)
  3. {
  4. Console.WriteLine("aisnegative.");
  5. }
  6. else
  7. {
  8. Console.WriteLine("ais0orpositive.");
  9. }

The {} brackets are optional for a single line statement.

  1. if(a<0)
  2. Console.WriteLine("aisnegative.");
  3. else
  4. Console.WriteLine("ais0orpositive.");
(Video) C# Tutorial: Full Course for Beginners 🎮 (FREE)

You can have a nested if . . .else statement with one of more else blocks.

You can also apply conditional or ( || ) and conditional and (&&) operators to combine more then one condition.

  1. inta=-1;intb=10;intc;
  2. //Checkifbothnumbersarenegative
  3. if(a<0&&b<0)
  4. {
  5. Console.WriteLine("Bothaandbarenegative.");
  6. }
  7. elseif(a<0||b<0)
  8. {
  9. Console.WriteLine("Onenumberisnegative.");
  10. }
  11. else
  12. {
  13. Console.WriteLine("Bothnumbersarepositive.");
  14. }

The if..else statement can have other nested statements and also can have more than one if..else statements.

19. C# switch Statement

C# switch statement is a conditional statement that pairs with one or more case blocks and a default block. The case block of code is executed for the matching value of switch expression value. If the switch value doesn’t match the case value, the default option code is executed.

  1. switch(expression)
  2. {
  3. caseexpression_value1:
  4. Statement
  5. break;
  6. caseexpression_value2:
  7. Statement
  8. break;
  9. caseexpression_value3:
  10. Statement
  11. break;
  12. default:
  13. Statement
  14. break;
  15. }

The expression in the above code can be any non-null expression.

The following code is a typical switch statement. The switch expression is a random number between 1 and 9 and based on the value of the expression, a case block is executed. If the value of switch expression is more doesn’t match with first three case values, the default block is executed.

  1. //Generatearandomvaluebetween1and9
  2. intcaseSwitch=newRandom().Next(1,9);
  3. switch(caseSwitch)
  4. {
  5. case1:
  6. Console.WriteLine("Case1");
  7. break;
  8. case2:
  9. Console.WriteLine("Case2");
  10. break;
  11. case3:
  12. Console.WriteLine("Case3");
  13. break;
  14. default:
  15. Console.WriteLine("Valuedidn’tmatchearlier.");
  16. break;
  17. }

Here is a detailed tutorial on switch statement:C# Switch Statement

20. C# for Statement

The for statement also knows as the for loop executes a block of code.

Syntax of for loop:

for (initializer; condition; iterator)

statement

This code is the simplest example of a for loop. In this code, the variable counter is initialized to value 0. The condition is until counter is less than or equal to 100, add +1 to counter. The code block displays the value of counter to the console.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("forloopSample!");
  7. //Forloopfrom0to100
  8. for(intcounter=0;counter<=100;counter++)
  9. Console.WriteLine(counter);
  10. Console.ReadKey();
  11. }
  12. }

The initializer defines the initial value to start with and the iterator is the increment or decrement. The following code snippet starts a loop from 10 to less than 100 in increments of 10.

  1. for(intcounter=10;counter<=100;counter+=10)
  2. {
  3. Console.WriteLine(counter);
  4. }

The statement part of the loop has a code of block that will be executed when the condition is met. The following code blocks checks for the even numbers between 10 and 100.

  1. for(intcounter=10;counter<=100;counter+=10)
  2. {
  3. if(counter%2!=0)
  4. {
  5. Console.WriteLine(counter);
  6. }
  7. }

21. C# foreach Statement

The foreach statement is used to iterate through a collection of items such as an array. The foreach body must be enclosed in {} braces unless it consists of a single statement. We will discuss arrays and collections later in this book.

The following code creates an array of odd numbers and uses foreach loop to loop through the array items and read them.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("foreachloopSample!");
  7. int[]oddArray=newint[]{1,3,5,7,9,11,13,15,17,19,21};
  8. foreach(intnuminoddArray)
  9. {
  10. Console.WriteLine(num);
  11. }
  12. Console.ReadKey();
  13. }
  14. }

Here is an example of for loop that can also be used read an array items.

  1. for(intcounter=0;counter<oddArray.Length;counter++)
  2. {
  3. Console.WriteLine(oddArray[counter]);
  4. }

Here is a detailed tutorial on foreach:C# foreach loop

22. C# do..while Statement

The do..while statement executes a block of code until the specified while condition is false. The code body must be enclosed in {} braces unless it consists of a single statement.

The following code continues a loop until the counter is less than 20.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("do..whileloopSample!");
  7. intcounter=0;
  8. do
  9. {
  10. Console.WriteLine(counter);
  11. counter++;
  12. }while(counter<20);
  13. Console.ReadKey();
  14. }
  15. }

23. C# while Statement

The while statement executes a block of code until the specified while condition is false. The code body must be enclosed in {} braces unless it consists of a single statement.

The following code continues a loop until the counter is less than 20.

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("do..whileloopSample!");
  7. intcounter=0;
  8. while(counter<20)
  9. {
  10. Console.WriteLine(counter);
  11. counter++;
  12. }
  13. Console.ReadKey();
  14. }
  15. }

24. C# go to Statement

The goto statement is used when you need to jump to a particular code segment. The following code uses a goto statement to jump from one case block to another once a condition is met. The program reads a string from the console. When you type, ‘Mahesh’, the case statement sends control to case statement, ‘Chand’.

Note that when using a go to in a case statement, you don’t have to provide a break (in all other cases, a break statement is mandatory).

  1. usingSystem;
  2. classProgram
  3. {
  4. staticvoidMain(string[]args)
  5. {
  6. Console.WriteLine("HelloWorld!");
  7. Console.WriteLine("Whatisyourname?");
  8. stringname=Console.ReadLine();
  9. switch(name)
  10. {
  11. case"Mahesh":
  12. Console.WriteLine("MynameisMahesh.");
  13. gotocase"Chand";
  14. case"Chand":
  15. Console.WriteLine(@"Chandismylastname.");
  16. break;
  17. case"Neel":
  18. Console.WriteLine("MynameisNeel.");
  19. break;
  20. default:
  21. break;
  22. }
  23. Console.ReadKey();
  24. }
  25. }

25. C# break Statement

The break statement exits from a loop or a switch immediately. The break statement is usually applicable when you need to release control of the loop after a certain condition is met, or if you want to exit from the loop without executing the rest of the loop structure. You use it in for, foreach, while, and do. . . while loop statements. The following code shows the break statement. If condition num == 15 is true, the control will exit from the loop.

  1. //Arrayofoddnumbers
  2. int[]oddArray=newint[]{1,3,5,7,9,11,13,15,17,19,21};
  3. //Loopthrougharrayitems
  4. foreach(intnuminoddArray)
  5. {
  6. Console.WriteLine(num);
  7. //Don'treadanynumberafter15
  8. if(num==15)break;
  9. }

26. C# continue Statement

Similar to the break statement, the continue statement also works in for, foreach, while, and do . . . while statements. The continue statement causes the loop to exit from the current iteration and continues with the rest of the iterations in the loop.

  1. for(intcounter=0;counter<=10;counter++)
  2. {
  3. if(counter==5)
  4. continue;
  5. Console.WriteLine(counter);
  6. }

In the above code, when the condition counter == 5 is true, the control exits from the current iteration and moves to the next iteration.

27. C# return Statement

The return statement returns from a method before the end of that method is reached. The return statement can either a value or not, depending on the method that calls it.

The following code is an example of a return statement. The execution goes to the caller program of the method.

  1. if(counter==9)
  2. return;

28. C# Interface

An interface is a blueprint that an implementing class or struct must implement. An interface contains only the signatures of its members. Interfaces are used by library and component developers when certain blueprint of the classes or structs must be followed by the implementing developers.

An interface has the following properties:

  • Any class or struct that implements the interface must implement all its members.
  • An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.
  • Interfaces can contain events, indexers, methods, and properties.
  • Interfaces contain no implementation of methods.
  • A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
  • The corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
  • Interfaces can also have base interfaces and an interface can inherited from more than one base interfaces.

Learn more here: Interface In C#

29. C# Partial Class

Partial classes were introduced in C# 2 that allows developers to split a class into multiple physical files. Partial classes come handy in large projects and a class size is too large and functionality is distributed among multiple members in a team.

In large projects, multiple team members work on same area of functionality. Let’s assume that an application has a user interface (UI), a window or a page. The UI has ton of functionality where multiple developers needs to work on the same window functionality. One developer will create the user interface, change design and layout, while other two developers may work on the database and business logic functionality. We can easily separate the window code into three physical partial classes and each developer can work on a separate class.

Learn more here:Partial Classes In C# with Real Example

(Video) C# Fundamentals for Beginners

30. C# Static Class

Static classes don’t have instance constructors and are used direct without creating an instance. Here are static classes properties.

  • A static class cannot be instantiated. That means you cannot create an instance of a static class using new operator.
  • A static class is a sealed class. That means you cannot inherit any class from a static class.
  • A static class can have static members only. Having non-static member will generate a compiler error.
  • A static class is cannot contain instance constructors.
  • A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

Learn more here: Static Class In C#

31. C# Abstract Class

The purpose of an abstract class is to define a blueprint of derived classes. Abstract classes do not have any implementation. The classes that are inherited from an abstract class implements the class functionality.

Here are the key characteristics of abstract classes:

  • An abstract class cannot be instantiated.
  • A class may inherit one abstract class only.
  • An abstract class may contain abstract methods, properties, and events.
  • An abstract class can’t be modified with the sealed class modifier.
  • A derived from an abstract class must implement all inherited abstract methods and accessors.

Learn more here:Abstract Class In C#

32. C# array

An Array in C# is a collection of objects or types. C# Array elements can be of any type, including an array type. An array can be Single-Dimensional, Multidimensional or Jagged. A C# Array can be can be declared as fixed length or dynamic. An Array in C# can be a single dimension, multi dimension, or a jagged array. Learn how to work with arrays in C#.

In C#, an array index starts at zero. That means the first item of an array starts at the 0thposition. The position of the last item on an array will total number of items - 1. So if an array has 10 items, the last 10thitem is at 9thposition.

In C#, arrays can be declared as fixed length or dynamic. Afixed lengtharray can store a predefined number of items. Adynamic arraydoes not have a predefined size. The size of adynamic arrayincreases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.

The following code snippet creates an array of 3 items and values of these items are added when the array is initialized.

  1. //Initializeafixedarray
  2. int[]staticIntArray=newint[3]{1,3,5};

    Here is a detailed tutorial on Arrays: Working with Arrays In C#

    33. C# string

    The System.String data type represents a string in .NET. A string class in C# is an object of type System.String. The String class in C# represents a string.

    The following code creates three strings with a name, number,and double values.

    1. //Stringofcharacters
    2. System.StringauthorName="MaheshChand";
    3. //StringmadeofanInteger
    4. System.Stringage="33";
    5. //Stringmadeofadouble
    6. System.StringnumberString="33.23";

    Here is the complete example that shows how to use stings in C# and .NET.

    1. usingSystem;
    2. namespaceCSharpStrings
    3. {
    4. classProgram
    5. {
    6. staticvoidMain(string[]args)
    7. {
    8. //Define.NETStrings
    9. //Stringofcharacters
    10. System.StringauthorName="MaheshChand";
    11. //StringmadeofanInteger
    12. System.Stringage="33";
    13. //Stringmadeofadouble
    14. System.StringnumberString="33.23";
    15. //WritetoConsole.
    16. Console.WriteLine("Name:{0}",authorName);
    17. Console.WriteLine("Age:{0}",age);
    18. Console.WriteLine("Number:{0}",numberString);
    19. Console.ReadKey();
    20. }
    21. }
    22. }

    Here is a detailed tutorial on strings: String In C#

    34. C# List

    List<T> class in C# represents a strongly typed list of objects. List<T> provides functionality to create a list of objects, find list items, sort list, search list, and manipulate list items. In List<T>, T is the type of objects.

    List<T> is a generic class and is defined in the System.Collections.Generic namespace. You must import this namespace in your project to access the List<T> class.

    1. usingSystem.Collections.Generic;

    List<T> class constructor is used to create a List object of type T. It can either be empty or take an Integer value as an argument that defines the initial size of the list, also known as capacity. If there is no integer passed in the constructor, the size of the list is dynamic and grows every time an item is added to the array. You can also pass an initial collection of elements when initialize an object.

    This code snippet 1 creates a List of Int16 and a list of string types. The last part of the code creates a List<T> object with an existing collection.

    1. //Listwithdefaultcapacity
    2. List<Int16>list=newList<Int16>();
    3. //Listwithcapacity=5
    4. List<string>authors=newList<string>(5);
    5. string[]animals={"Cow","Camel","Elephant"};
    6. List<string>animalsList=newList<string>(animals);

      As you can see from Listing 1, the List<string> has an initial capacity set to 5 only. However, when more than 5 elements are added to the list, it automatically expands.

      Here is a detailed tutorial on list. C# List Tutorial

      35. C# dictionary

      The Dictionary type represents a collection of keys and values pair of data.

      C# Dictionary class defined in the System.Collections.Generic namespace is a generic class and can store any data types in a form of keys and values. Each key must be unique in the collection.

      Before you use the Dictionary class in your code, you must import the System.Collections.Generic namespace using the following line.

      1. usingSystem.Collections.Generic;

      The Dictionary class constructor takes a key data type and a value data type. Both types are generic so it can be any .NET data type.

      The following The Dictionary class is a generic class and can store any data types. This class is defined in the code snippet creates a dictionary where both keys and values are string types.

      1. Dictionary<string,string>EmployeeList=newDictionary<string,string>();

      The following code snippet adds items to the dictionary.

      1. EmployeeList.Add("MaheshChand","Programmer");
      2. EmployeeList.Add("PraveenKumar","ProjectManager");
      3. EmployeeList.Add("RajKumar","Architect");
      4. EmployeeList.Add("NipunTomar","Asst.ProjectManager");
      5. EmployeeList.Add("DineshBeniwal","Manager");

        Here is a detailed tutorial on dictionary:Dictionary In C#

        36. Summary

        This tutorial is an introduction to C# language for beginners. In this tutorial, we learned how to write our first C# program, basics of data types, classes, objects, and class members.

        Download free C# Programming eBook:

        Free Book: C# Programming for Beginners

        (Video) C# Full Course - Learn C# 10 and .NET 6 in 7 hours

        FAQs

        Is C sharp easy to learn for beginners? ›

        C# is one of the easiest programming languages to learn. C# is a high-level, general-purpose programming language that is easy to read because of its well-defined class hierarchy. It is the perfect language for beginner developers as it will be straightforward to grasp compared to most other languages.

        What is the easiest way to learn C#? ›

        C# was created by Microsoft after all, so Microsoft Learn is one of the best ways for beginners to start learning. In this course with free certificate, you'll learn the basic syntax and thought processes required to build simple applications using C# through interactive tutorials.

        How long will it take me to learn C sharp? ›

        If you already have a background in coding, you can expect to take anywhere from 2 to 3 months to learn the very basic of C# programming. Building the skills and knowledge you need to get a job as a developer, on the other hand, will take you around 1 to 2 years of practice.

        What should I learn first in C#? ›

        Key Topics:
        1. Creating and understanding your first C# program.
        2. Understanding Data types and Variables.
        3. Understanding Arrays.
        4. Working with Strings.
        5. Learning how to work with Date and Time data.
        15 Aug 2019

        Can I learn C# in a day? ›

        Concepts are presented in a "to-the-point" style to cater to the busy individual. With this book, you can learn C# in just one day and start coding immediately. The best way to learn C# is by doing.

        Is C# or Python harder? ›

        While Python is easier to learn and write than C# and has vast standard libraries. Both C# and Python are excellent programming languages. Thus, picking one over the other is more a matter of preference than the risk of choosing the wrong language for the project.

        Can I learn C# without knowing anything? ›

        Yes, of course. Everyone starts with something and c# is a good platform (. net) but not so onerous as c++ .

        Can I learn C# in a month? ›

        If you have experience with object oriented programming, you should be fine spending a day or two learning the syntax of C# and be competent enough to be employed. If you have never programmed before, then maybe 6 months to a year?

        Is C# easier than C++? ›

        Difficulty. Many professionals believe that C++ is very complex, whereas C# is easy because of its well-defined class hierarchy. Because C# is a high-level programming language , its code is easy to read. This is key for beginning developers, as they might enjoy the language's simple hierarchy.

        Can I learn C in 20 days? ›

        You can learn C in just 20 days or you can extend that to 45 days also. There is no fixed interval to learn the language.

        Can I learn C# in a week? ›

        “If you have experience programming...it would take you a week to learn C#. One week, really,” Činčura says. “It's not a difficult language. You don't have to know all the bells and whistles.

        How do I master in C#? ›

        The best way to learn C# is with a combination of an introduction to the language concepts followed immediately by practice in the form of exercises. Read about/watch a video about/learn about a new concept. Write a small program (or expand an existing one) in which you reinforce the learning with applied practice.

        Is C# easier than Java? ›

        C# is easier because the language, the runtime, most of the important libraries and the IDE come from a single source - Microsoft. The result of this is that you get started quickly and things usually work smoothly and efficiently. Java is richer because it is used by most open source projects.

        Is C# harder to learn than C? ›

        There're too many habits you'll struggle with later. If you're only going to learn one, then C# is easier and faster to learn. But if you think that you might someday need more, then C++ will make you better prepared. I've been programming for 25 years and have seen languages come and go.

        Should I learn C++ first or C#? ›

        If performance is your top priority, then C++ is the way to go. If performance doesn't matter that much, you prefer not to get bogged down coding the details of everything, and you want the project done quickly, then you should go with C#.

        Is C# still in demand? ›

        Also, C# is growing in popularity among developers creating mobile apps; this means we'll likely see a significant increase in C# use as mobile applications are already in significant demand worldwide and only will continue to be more so.

        Is C# faster then Python? ›

        As a compiled language, C# converts directly into machine code that a processor can execute. No interpreter needed. In some cases, this means that C# code can run up to 44 times faster than Python. And whilst you can speed up Python's performance significantly with PyPy's JIT compiler, C# still holds its lead here.

        Is it worth learning C# in 2022? ›

        Is C# worth learning in 2022? C# is being integrated into every platform, including desktop, online, future technologies, gaming, and services. So, absolutely, you should study C# right now since it will offer you the best chance of getting in and will keep you employed as you advance in your career.

        Which programming is the toughest? ›

        C++ C++ is considered to be one of the most powerful, fastest, and toughest programming languages.

        Which pays more C# or Python? ›

        Python vs C# Salary

        According to the Stack Overflow survey, Python developers earn on average $120k a year, and C# developers make $110k a year.

        Which programming is the hardest? ›

        Malbolge: One esoteric programming language is Malbolge.

        The fact that it took at least two years to complete developing the first Malbolge code indicates that it is by far the toughest programming language to learn.

        Can I get a job if I only know C#? ›

        Very much! If you're a good C# programmer, you can get a 6-figure job in the U.S. easily. You can use C# for Windows programs, Web Programming, Mobile-Phone programming with Xamarin and even video games with Unity.

        Do you need math for C#? ›

        Also, studying Computer Science or Computer Engineering involves a lot of math, but this is not really necessary on the field. 90% of a CS degree involves studying things that are really interesting, sure, but hardly practical. You need math to understand the underlying theory.

        Should I learn Java or C# first? ›

        NET framework is robust. However, C# is a better fit for more experienced programmers. If you're a beginner in programming, I would recommend learning Java. The general-use characteristic makes it a more realistic, worthwhile investment, just in case you want to keep your options open.

        Is C sharp difficult to learn? ›

        C# is relatively easy to learn. Since it omits many of the complex tasks in programming, a programmer doesn't have to worry about these potential issues ahead of time and can just start coding.

        Is C sharp low level? ›

        C# language is considered a high-level language because its syntax resembles human language. In other words, it has a high level of abstraction from a machine code, which is why we need to compile the code written in C# for the hardware to understand its commands.

        Is C# fast enough? ›

        It depends on your intended use. If your project is a web or desktop app that needs an efficient programming language, C# would be better. On the other hand, if you want speed, C++ might be the key. Many developers who work on video games use C++ because of how fast it is.

        What is C# best used for? ›

        C# is considered a general-purpose programming language used to build different types of applications and web-based services. Due to its speed and ease of use, it is popular among developers and it is applied in backend services, Windows apps, website development, and game development.

        Is C the hardest language to learn? ›

        No, C is not the most difficult language. Coding is not hard to learn in general. However, the programming language is relatively challenging to learn. If you are a beginner in programming, you can start by building a solid foundation in computer science before progressing to C.

        Which language should I learn first? ›

        Python is known for being easy to learn, making it a great first language to learn. Python is used in the following: Server-side development. Data analysis and machine learning.

        Can you learn code in 3 months? ›

        Most coders agree that it takes three to six months to be comfortable with the basics of coding. But you can learn coding faster or slower depending on your preferred pace. Let's get into the specific skills you'll need to learn.

        Is C# a good career? ›

        Conclusion. To sum it up, you will have a great career if you decide to choose C# as a language of choice. The biggest benefit is the variety of applications you can work on and companies that use C#.

        Is C# high paying? ›

        Salary Ranges for C# Developers

        The salaries of C# Developers in the US range from $60,000 to $160,000 , with a median salary of $80,000 . The middle 57% of C# Developers makes between $80,000 and $105,000, with the top 86% making $160,000.

        Why is C# complicated? ›

        Most of the 'complexity' in C# comes probably from it being an object-oriented language, which brings more concepts to master likes classes, interfaces, inheritance, polymorphism, generics, etc.., which makes them a tad more complex but really help when building large-applications.

        Which has more job opportunities Java or C#? ›

        Should I specialize in C# or Java? Professionally, Java would be the better choice. It is, by far, the most popular programming language in the world. There are far more job postings for Java than for any other language.

        Is C# or C++ better? ›

        C++ code is much faster than C# code, which makes it a better solution for applications where performance is important. For instance, your network analysis software might need some C++ code, but performance is probably not a huge issue for a standard word processing application coded in C#.

        Is C# better than Java? ›

        C# is generally considered faster than Java, although the difference is insignificant. Both languages are compiled, but C# uses a just-in-time compiler while Java uses an ahead-of-time compiler. This means that C# code is typically executed more quickly.

        Is C# easy if you know C? ›

        C# is a general-purpose, object-oriented programming language that is structured and easy to learn. It runs on Microsoft's . Net Framework and can be compiled on a variety of computer platforms. As the syntax is simple and easy to learn, developers familiar with C, C++, or Java have found a comfort zone within C#.

        What games are written in C#? ›

        Popular Games Made with C#
        • Stardew Valley.
        • Cuphead.
        • Hearthstone.
        • Osiris: New Dawn.
        22 Feb 2022

        Should I learn C# or C++ as a beginner? ›

        Both of them can be used in web and desktop applications, but C# is much more popular now for both applications. C++ is considered a more prestigious language used for applications such as games, operating systems, and very low-level programming that requires better control of hardware on the PC or server.

        Can I learn C# without knowing C? ›

        While you can choose to do this if you want to gain an in-depth knowledge of these programming languages, you certainly don't need to know C to learn C#. It's helpful for students to start by learning C# first (even if they eventually want to learn C) because it's simpler and easier to use.

        Is C# or C++ easier to learn? ›

        Difficulty. Many professionals believe that C++ is very complex, whereas C# is easy because of its well-defined class hierarchy. Because C# is a high-level programming language , its code is easy to read. This is key for beginning developers, as they might enjoy the language's simple hierarchy.

        Is C# enough to get a job? ›

        You might get better tooling and more support for some trendy machine learning and big data frameworks but you won't be building nice desktop clients for Windows. Also, the language standard and the language features are a bit behind C#. In overall, not a bad career choice either.

        Which is the toughest computer language? ›

        C++ C++ is considered to be one of the most powerful, fastest, and toughest programming languages.

        Which is harder C or C#? ›

        If you're only going to learn either C++ or C#, then you should probably go with C# because it's easier and faster to learn and widely applicable. There's nothing wrong with only learning C# and you can write any type of software with the language.

        Is C# still relevant 2022? ›

        Is C# worth learning in 2022? C# is being integrated into every platform, including desktop, online, future technologies, gaming, and services. So, absolutely, you should study C# right now since it will offer you the best chance of getting in and will keep you employed as you advance in your career.

        Is C# in demand? ›

        In-Demand Skill

        Many major companies use C# daily to build software programs. This means C# skills are in high demand.

        What is the hardest part of C#? ›

        In C#, the hardest feature is easily generic covariance and contravariance. Go here, scroll down and read the blog posts one by one from bottom to top. Make sure you understand every word of it, in particular all the examples. Warning: your brain will hurt.

        What pays more Java or C#? ›

        C# vs Java: popularity and talent pool

        NET developers have a bit fewer opportunities. According to Glassdoor, an average Java programmer's salary in the US is approximated at $79,000, while C#.NET devs make less on average with $68,500.

        Is C# well paid? ›

        C# is one of the programming languages designed for the Common Language Infrastructure. C# programmers can earn 107k dollars a year.

        Videos

        1. Learn C# BASICS in 10 MINUTES!
        (Code Monkey)
        2. How to Program in C# - BASICS (E01)
        (Brackeys)
        3. Learning Unity Be Like
        (Mults)
        4. C# While Loop Tutorial for Beginners
        (DJ Oamen)
        5. Learn 2-5-1 chord voicings in key of C, C#, F,F# that pro use | Piano Tutorial
        (Olusegun Johnsonkeyz (Piano and Music Lessons))
        6. How To Play Made You Look - Meghan Trainor Guitar Tutorial (Beginner Lesson!)
        (BMartinSounds - Easy Guitar Tutorials)
        Top Articles
        Latest Posts
        Article information

        Author: Tish Haag

        Last Updated: 03/15/2023

        Views: 6627

        Rating: 4.7 / 5 (67 voted)

        Reviews: 90% of readers found this page helpful

        Author information

        Name: Tish Haag

        Birthday: 1999-11-18

        Address: 30256 Tara Expressway, Kutchburgh, VT 92892-0078

        Phone: +4215847628708

        Job: Internal Consulting Engineer

        Hobby: Roller skating, Roller skating, Kayaking, Flying, Graffiti, Ghost hunting, scrapbook

        Introduction: My name is Tish Haag, I am a excited, delightful, curious, beautiful, agreeable, enchanting, fancy person who loves writing and wants to share my knowledge and understanding with you.