C#.Net tutorial for beginners with examples

In this C#.Net tutorial for beginners with examples, we will see various C#.Net tutorial with examples. We will discuss below things:

Common Language Runtime in C#.Net

Now, we will discuss Common Language Runtime in C#.Net.

  • The CLR is the engine that supports all the .NET languages. All .NET code runs inside the CLR.
  • When a client requests an ASP.NET web page, the ASP.NET service runs inside the CLR environment, executes your code, and creates a final HTML page to send to the client.
  • CLR has deep integration with different languages like VB.Net or C#.Net. It converts to IL code.
  • The CLR also has the ability to load more than one version of a component at a time. Multiple versions of the .NET Framework can be installed, meaning that you’re able to upgrade to new versions of ASP.NET without replacing the current version or needing to rewrite your applications.
  • It also helps improve performance. ASP.NET application is extremely fast because the ASP.NET code is compiled to machine code before it’s executed.
  • CLR provides exception handling, garbage collection and thread management.

Tuple in C#.Net 4.0

Let us now, discuss what is Tuple in C#.Net 4.0. There are some new features in .Net 4.0, one of these is Tuple.

  • Tuple actually a concept of F#, But in .Net 4.0 microsoft introduced Tuples to .Net.
  • Arrays combine objects of the same type; tuples can combine objects of different types.
  • .NET 4 defines eight generic Tuple classes and one static Tuple class.
  • Tuple can be instantiated by Tuple constructor or the static Tuple.Create() method.
  • Tuple.Create method has 8 overloads.

Here is an example that is provided in msdn:

var population = new Tuple(
"New York", 7891957, 7781984,
7894862, 7071639, 7322564, 8008278);

0r:

Tuple tuple = new Tuple(1, "EnjoySharePoint");

Loops in C#.Net

Let us now discuss Loops in C#.net. Loops help to repeat a segment of code multiple times in C#.Net.

C#.Net provides 4 types of loops.

  • for loop
  • for each loop
  • while loop
  • do…while loop

for Loop in C#.Net

Through for loop you to repeat a block of code a set number of times, using a built-in counter. To create a for loop, you need to specify a starting value, an ending value, and the amount to increment with each pass.

syntax:

for (int i = 0; i < 10; i++)
{
// Code which will execute 10 times.
}

for each Loop in C#.Net

The foreach loop allows you to loop through the items in a set of data. The code will then loop until you’ve had a chance to process each piece of data in the set.

Example:

int[] intArray = {1,2,3};
foreach (int num in intArray)
{
num += 1;
}

while loop in C#.Net

A while loop tests a specific condition before or after each pass through the loop. When this condition evaluates to false, the loop is exited.

int i = 0;
while (i < 10)
{
i += 1;
}

Here the loop will execute till the value of i >=10. Here it will loop 10 times.

do…while loop in C#.Net

The do..while syntax is also same. In case of C#.net do…while loop, the condition will be tested at the end of each pass through the loop.

syntax:

int i = 0;
do
{
i += 1;
}
while (i < 10);

The do…while loop will always execute the code at least once because it doesn’t test the condition until the end.

Enums in C#.Net

Now, let us see Enum in C#.Net and how to set enum values with spaces in c#.net?

The enum keyword is used to declare an enumeration in c#.net, a distinct type consisting of a set of named constants called the enumerator list. Every enumeration type has an underlying type, which can be any integral type except char.

The default underlying type of the enumeration elements is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.

we can declare an enum in c#.net like below:

enum WesiteList
{
AspDotNetHelp,
Fewlines4Biju,
OnlySharePoint2013,
SharePoint_Net,
EnjoySharePoint
}

Here in this enumeration AspDotNetHelp is o, Fewlines4Biju is 1 etc.

But you can initialize enumeration like below:

enum WesiteList
{
AspDotNetHelp=1,
Fewlines4Biju,
OnlySharePoint2013,
SharePoint_Net,
EnjoySharePoint
}

Here in this enumeration AspDotNetHelp is 1, Fewlines4Biju is 2 etc.

We can get the value like below:

int website = (int) WebsiteList.AspDotNetHelp;

.Net class library uses Enumeration hugly. Enums are value types and are created on the stack and not on the heap.

How to set enum values with spaces in c#.net?

Now, let us see how to set enum values with space in C#.Net.

If you will give space and declare like below then it will give an error.

public enum MonthYear
   {
       Jan 2014 = 0,
}

Here the error will come because of space between Jan 2014. So below is the syntax to declare enum values with space.

public enum MonthYear
   {
       [EnumMember(Value = “Jan 2014”)]
       Jan2014 = 0,
       [EnumMember(Value = “Feb 2014”)]
       Feb2014 = 0,
}

I hope this C#.Net tutorial helps to learn C#.Net enums and how to set enum values with spaces in c#.net?

Interfaces in C#.Net

Now, let us discuss Interfaces in C#.Net.

  • An interface looks like a class, but has no implementation. An interface describes methods, properties and events.
  • A class can implement more than one interface
  • C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

To declare a interface we have to use the keyword interface like below:

interface ITestInterface
{
void TestMethodToImplement();
}

As the declaration suggests, As a naming convention you can use a prefix with I in the interface name like ITestInterface.

  • Interface contains unimplemented methods.
  • Interfaces must be implemented by derived classes and structs.

Example below:

Class myClass : ITestInterface
{
void TestMethodToImplement()
{
//Method body will contain.
}
}
  • The class implements the interface must have to implement its members else the class has to be declared as Abstract class.
  • Interfaces may also be inherited by other interface.

Below is a way how a class can implement multiple interface:

Class myClass : ITestInterface, IInterface2
{
void TestMethodToImplement()
{
//Method body will contain.
}
void TestMethodInterface2()
{
//Method body will contain.
}
}

This is how we can work with C#.Net interfaces.

Array and ArrayList in C#.Net

Now, let us discuss array and arraylist in C#.Net.

C#.Net Array

Arrays allow you to store a series of values that have the same data type.
The values can be accessed by using its index number. And the index starts with 0 and the highest index is one less than the number of elements.

Below is a string array:

string[] stringArray = new string[5];

Here new keyword is used to initialize the array.

Also you can directly put the values like below:

string[] stringArray = {"1", "2", "3", "4","5″};

We can access the values like below:

string value = stringArray[3];

The value will be 4;

  • If you create an array, you can not resize the array.
  • If you declared an integer array then only integer can be stored, if you try to initialize any other thing then it will give an exception.

Similarly, you can create multi dimentional array like below:

int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8},{9,10}};

C#.Net ArrayList

ArratList supports any type of object and always allows dynamic resizing, means the size can be increased or decreased.

Syntax to create array:

ArrayList arr = new ArrayList();

Put the value like below:

arr.Add("Value1");
arr.Add("Value2");
arr.Add("Value3");

And we can retrieve the value like below:

string value = Convert.ToString(arr[1]);

This is how we can use Array and ArrayList in C#.Net.

Lock and Monitor statement in C#.Net

The benefit of using multiple threads in an application is that each thread executes asynchronously. For Windows applications, this allows time-consuming tasks to be performed in the background while the application window and controls remain responsive. For server applications, multithreading provides the ability to handle each incoming request with a different thread.

Since threads are asynchronous by nature access to resources such as file handles, network connections, and memory must be coordinated. Otherwise, two or more threads could access the same resource at the same time, each unaware of the other’s actions. The result is unpredictable data corruption.

The lock Keyword in C#.Net

The lock keyword can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

A lock statement begins with the keyword lock, which is given an object as an argument, and followed by a code block that is to be executed by only one thread at a time.

using System;
using System. Threading;
class emp
    {
        private Object myLock = new Object();
        int sal;
        Random rnd = new Random();
        public emp(int incentive)
        {
            sal = incentive;
        }
        int Withdraw(int amt)
        {
            // This condition  is true only if the lock statement is commented
            if (sal < 0)
            {
                throw new Exception(“-ve Balance Amount”);
            }
            // Comment  the next line to see the effect of leaving out
            // the lock keyword.
            lock (myLock)
            {
                if (sal >= amt)
                {
                    Console.WriteLine(“salary before Withdrawal :  ” + sal);
                    Console.WriteLine(“The amount to Withdraw        : -” + amt);
                    sal = sal – amt;
                    Console.WriteLine(“salary after Withdrawal  :  ” + sal);
                    return amt;
                }
                else
                {
                    return 0; // transaction  is rejected
                }
            }
        }
        public void calculate()
        {
            for (int k = 0; k < 50; k++)
            {
                Withdraw(rnd.Next(1, 50));
            }
        }
    }
class work
    {
        static void Main()
        {
            Thread[] threads = new Thread[10];
            emp e1 = new emp(100);
           for (int k = 0; k < 10; k++)
            {
               Thread t = new Thread(new ThreadStart(e1.calculate));
                threads[k] = t;
            }
            for (int k = 0; k < 10; k++)
            {
                threads[k].Start();
            }
        }
    }

The argument provided to the lock keyword must be an object based on a reference type and is used to define the scope of the lock. It is good practice to avoid locking on a public type, or on object instances beyond the control of your application.

For example, lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well. This could create deadlock situations where two or more threads wait for the release of the same object. it is best to lock a private or protected member that is not interned.

Monitor statement in C#.Net

Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit.

This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class.

For example:

lock (xyz)
{
DoSomething();
}
This is equivalent to:
System.Object obj = (System.Object)xyz;
System.Threading.Monitor.Enter(obj);
try
{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}

Using the lock keyword is generally preferred that the Monitor class directly, since the lock is more concise, and it insures that the underlying monitor is released, even if the protected code throws an exception. This is accomplished with the final keyword, which executes its associated code block regardless of whether an exception is thrown.

C#.Net tutorial for beginners with examples

Multithreading tutorial in C#.Net

C#.net supports parallel execution of code through multithreading. A thread is nothing but an execution path to run an application. Multithreading means more than one execution path to run a single application.

C#.Net program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system.

To convert the single-threaded application into a multithreaded, import System.Threading namespace in your application. Threads are created using the Thread class’s constructor, passing in a ThreadStart delegate which indicates where execution should begin.

using System;
using System.Threading;
class ThreadExample
{
  static void Main()
  {
    Thread t1 = new Thread (new ThreadStart (m1));
    t1.Start();   // Run  method m1() on the new thread.
    m1();        // Simultaneously run  method m1() in the main thread.
  }
  static void m1()
  {
    For(int i=1;i<=100;i++)
    Console.WriteLine ("the value of i is: {0}", i );
  }
}

This is how we can work with Multithreading in C#.Net.

Convert first letter to uppercase in C#.Net

Now, we will discuss how to convert first letter to upper case using C#.Net.

Below is the code that will convert first letter to upper case in C#.Net.

string enterWord = "aspDotNetHelp";
char[] allLetters =enterWord.ToCharArray();
allLetters[0] = char.ToUpper(allLetters[0]);
string result = new string(allLetters);

Here the output will come as below:

AspDotNetHelp

How To Call a Button Click From Another Button in C#.Net?

Now, we will see how to call a button click from another button click in C#.Net. Remember this is available in windows application not in a web application in .Net.

It is easy to call a button click on another button click. Check the full code below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnFirst_Click(object sender, EventArgs e)
{
lblResult.Text = "This is the First Button!";
}

private void btnSecond_Click(object sender, EventArgs e)
{
btnFirst.PerformClick();
}
}
}

Here in the second button click event we are calling the first button click and the result will be shown as “This is the First Button!”. Check the figure for output.

How To Call a Button Click From Another Button in C#.Net?

Set Enter and Esc Keys in Windows application C#.Net

Now, we will see, how to set Enter and Esc keys in C#.Net windows application.

Suppose I have a Windows Form and two buttons name as btnEnter and btnEsc. I want when the user clicks on entering, btnEnter should respond and similarly when the user clicks on Esc, btnEsc should respond.

Set Enter Key in Windows application C#.Net

For this Open windows form properties, from the properties window, select btnEnter in the AcceptButton properties as shown in the fig below:

Set Enter key in windows application C#.Net

Set Esc Key in Windows application C#.Net

For this Open windows form properties, from the properties window, select btnEsc in the CancelButton properties as shown in the fig below:

Set Esc key in windows application C#.Net

After that when you open the form, click on Enter key, btnEnter will fire and if you click on Esc, btnEsc code will fire.

How to Generate a Strong Name for the Assembly

Assemblies that host serviced components must be strong named. This procedure generates a public-private key pair used to strong name the assembly.

To generate a strong name for the assembly

Open a command window and go to the current project directory. Use the sn.exe utility to generate a key file that contains a public-private key pair.

sn.exe -k RajSimpleComponent.snk

In Visual Studio, open assemblyinfo.cs.

Locate the [AssemblyKeyFile] attribute and modify it to reference the key file in the project directory as follows.

[assembly: AssemblyKeyFile(@"..\..\RajSimpleComponent.snk")]

Build the Assembly and Add it to the Global Assembly Cache

This procedure builds the assembly that contains the serviced component and then adds it to the global assembly cache. Serviced components should generally be registered in the global assembly cache because they are system level resources.

To build the assembly and add it to the global assembly cache

On the Build menu, click Build Solution.

Return to the command window and run the following command to add the assembly to the global assembly cache.

gacutil –i bin\debug\RajtestCom.dll

Here, we learned how to Generate a Strong Name for the Assembly and how to Build the Assembly and Add it to the Global Assembly Cache?

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SPGuides.com

>