C#.Net Tutorial (Step by Step Guide)

C#.Net tutorial
SharePoint deveopment training course

Learn C#.Net from basics in this C#.Net tutorial. This is a step by step guide to learn C#.Net. If you want to learn C#.Net, then read this tutorial from start to end.

This C#.Net tutorial, we will discuss the basic of .Net for beginners. We will learn what is .net and why.net came in the picture? We will also learn what is C# and how to develop an application using .net.?We will get to know the difference between C++ and C# language?

This tutorial also help us to know about what is Visual Studio IDE and how to work with VisualStudio 2017? We will understand in the Visual Studio IDE how to create a console application using C#.Net.

We will see the Programming structure of C# .net? How to add a class in C# .net program. We will understand what is C#.net variable and variable naming convention and declaration of a variable. We will also see how to assign value to a variable and the different type of variable.

This C#.Net blog explains, what is C# data type and what is Implicitly Typed Local Variable. We will get to know about C#. net Operator, increment and decrement operator, and Postfix and prefix operator. We understand the Operator Predicence, adding parenthesis. We will read the C# various keyword.

This article helps us to know about what is C# .net variable, variable naming convention, declare a variable and assign value to a variable and what is the type of variable C# have? We will also learn What are the C#.net data type? C#.net Implicitly type of the local variable and what are the operators? C#.net increment and decrement variable and postfix and prefix increment and decrement operator? We will read Operator precedence and what is the use of adding parenthesis?

This blog teaches us what is .net methods, how to declare a method, return statement, how to call a method, an example of no argument no return type and having an argument and no return type. We will also know method overloading and overriding, cal by value and reference.

We will see C#.net conditional statement, different loops, what is array, declare, assign and initialize the array. How to access the array element in C#.net? using for each loop how to access the element in Array, 1Dand multidimensional array. We will read the enum keyword and what is a string and different string method is c#.net.

SharePoint 2016 Tutorial Contents

What is .Net?

Microsoft Provide a Software or product is called .Net which is used for developing various kind of application such as

  • Web application
  • Desktop application
  • Mobile application

Why .Net Came in the picture?

Previously we are using the C and C++ language for app development. But the drawback is, it’s only developing the window application but the Web application and mobile application is not possible. So for the web application, we need to know another language such as PHP, JavaScript, CGI, etc. Like that for mobile application again we need to read another language like Java.

As a developer, it is difficult to remember all languages syntax. So based on the limitation Microsoft developed the .Net software. Using the .Net software we can develop all type of application, mobile application, desktop application, and web application.

Features of Microsoft .Net

Below are the different features of Microsoft .Net.

Interoperability
Because interaction between new and older applications is commonly required, the .NET Framework provides means to access functionality that is implemented in programs that execute outside the .NET environment. Access to COM components is provided in the System.Runtime.InteropServices and System.EnterpriseServices of the framework.

Common Runtime Engine
Programming languages on the .NET Framework compile into an intermediate language known as the Common Intermediate Language (CIL). In Microsoft’s implementation, this intermediate language is not interpreted but rather compiled in a manner known as just-in-time compilation (JIT) into native code.

Language Independence
The .NET Framework introduces a Common Type System, or CTS. The CTS specification defines all possible datatypes and programming constructs supported by the CLR and how they may or may not interact with each other. Because of this feature, the .NET Framework supports the exchange of instances of types between programs written in any of the .NET languages.

Base Class Library
The Base Class Library (BCL), part of the Framework Class Library (FCL), is a library of functionality available to all languages using the .NET Framework. The BCL provides classes which encapsulate a number of common functions.

Portability
The design of the .NET Framework allows it to theoretically be platform agnostic, and thus cross-platform compatible. That is, a program written to use the framework should run without change on any type of system for which the framework is implemented. Microsoft’s commercial implementations of the framework cover Windows.

Memory management
It is the act of managing computer memory. In its simpler forms, this involves providing ways to allocate portions of memory to programs at their request, and freeing it for reuse when no longer needed.

The management of the main memory is critical to the computer system. In this process, it uses the Garbage Collection which is the automated allocation, and deallocation of computer memory resources for a program.

This is generally implemented at the programming language level and is in opposition to manual memory management, the explicit allocation, and deallocation of computer memory resources.

In computer science, garbage collection (GC) is a form of automatic memory management.

Components of .Net Framework

Below are the components of the .net framework.

.NET Framework is composed of various things like:

The .NET languages:
There are various languages supported by.Net framework like vb.net, c#.net, F#, J# etc. Apart from this also there are some 3rd party languages supported by.Net framework.

Common Language Runtime (CLR):
CLR executes all .NET programs and provides automatic services for these applications, such as security checking, memory management, and optimization.

The .NET Framework class library:
Microsoft provides thousand of classes and namespaces to work with .net. These classes contain some prebuilt functionality which you can use while developing. Like to work with database Microsoft provides some classes known as Ado.Net classes.

ASP.NET:
Asp.Net helps us to create web applications or MVC applications using.Net framework.

Visual Studio:
This is a tool which is very much helpful in quick development. This includes the complete .net framework.

How to develop an application using .Net or What is C#?

Microsoft provided a set of Programing language around more than 30 languages under .Net. So that all background people can work with .Net software.

For example, the people who came from the C and C++ background Microsoft provide the C# language for them. Like that for VB background people Microsoft provides VB.Net. So for using the.Net framework user has multiple options according to the comfort ness can choose the language.

C#.Net is one of language Microsoft provided to develop various application and run on .Net. C#.Net is high level and purely object-oriented programming language. It is the extension of C++ language. Whatever feature is available in C++ all are available in C#, with some additional feature. C#.net is developed for command language interface which consists of executable code and runs time environment.

The C# language is approved by ECMA (European Computer Manufacturers Association) and ISO (International Standards Organization. The latest version of C# is C# 7.3 which is released in 2018.

Difference between C#.Net and C++?

Now we will see what are the difference between the C#.Net and C++ programing language.

The C# .net Language:

  • C# provides High-level object-oriented programming language.
  • Memory management operation is performed automatically in C# using the Garbage collector.
  • C# does not support multiple inheritances through the class.
  • C# can not create a Standalone application.
  • C# is a pure object-oriented language.
  • C#run only when it is standardized.
  • C# supports for each loop.
  • In the C# .net language pointer only be used in unsafe mode.
  • After Compilation the C#.net language converted into intermediate code language.

The C++ programming language:

  • C++ provides low-level language.
  • Memory Management manually. The program is responsible for memory management.
  • C++ supports multiple inheritances in the class.
  • C++ create a standalone application.
  • C++ is not a completely object-oriented language because of its primitive data type.
  • C++ runs on all the Platform.
  • C++ does not support the for each loop
  • The Pointer can be used anywhere in the program in C++.
  • After Compilation the C++ language converted into machine code

What is Visual Studio?

Microsoft Provide an IDE for developing the .net Application. IDE stands for an integrated development environment. Just like the Turbo C IDE for C language. The Visual Studio IDE allows us to develop various kind of application such as Console Application, Web Application, web services, window services, windows application, etc.

As we know .Net is a collection of languages, by using the VisualStudio we can develop a different type of application using a different type of languages. That means we can use the same VisualStudio IDE for C#, F#, VB Script. The latest version of Visual Studio is Visual Studio 2019.

Visual studio 2019 comes with 3 editions:

  • Community Edition: This is a FREE visual studio IDE for students, open source contributors, and individuals
  • Professional Edition: This visual studio 2019 IDE is best for small teams.
  • Enterprise Edition: Visual studio 2019 enterprise edition is for teams of any size.

Create a Console Application using Visual Studio 2019/2017

We will see now how to start with the visual studio IDE with a Console Application example. Follow the below things to create a console application.

First in the Window bar search for Visual Studio. Click on Visual Studio 2017/2019.

c sharp tutorial
visual studio 2019 download

When we clicked on the Visual studio automatically the IDE page will open where we can develop a different type of application. From the menu bar click on File -> New -> Project.

c# visual studio tutorial
c# visual studio tutorial

Now the New Project window will come. In the left side panel, we can see different language like Visual C#, Visual Basic, Visual F#. Choose “Visual C#”, Click on it. When we clicked on the Visual C# it will display the related project template to develop an application in the right-hand side. Select the Console application (.Net Framework). Do not choose Console App (.NetCore). When We select the console application on the right-hand side we can see the description of the application.

The console application will run in a Window Command prompt, it will not run on the Graphical user interface.

In the button of the page we can see 3 fields.

Name: Give the name for the project. Whatever you want give the name.

Location:Browse one location where you want to save the application.

Solution Name: Give the name in the Name field same will come in the Solution name field. The solution is a root label element, one solution contains more than one Projects.

Make sure that the Create Directory for solution should be checked, actually that is by default checked. Clear the Add to source control.

Click on OK.

c sharp tutorial
visual studio 2017 c# tutorial

Now Program window will open.

The Program structure of C#

The C# Program contains below the element.

Class: The Class keyword is used to declare and define a class. In the below code using the class keyword, the program class is declared automatically.

Comments: In the below code no comments keyword is present but we need to know what is a comment. The purpose of Comments is to developer understanding. It will not execute in our program.

NameSpace: Generally, the Namespace is used for grouping the classes. For example, we have 10 classes and we want to group the 5 projects in one group and the next 5 projects in another group. Then we can use one namespace for 5 classes and another namespace for the rest 5 classes. In the below coding the Program class group under one namespace.

What we have given the project name the same name will come as a namespace name we can change the namespace name.

Using Statement: Using statement is the beginning of C#. Like the Program class, the .net contains various predefined classes and all the classes are defined under some namespace. So to consume the classes in our application the namespace are imported by default in our program. When namespaces have imported all the classes under the namespace will consume in our code. The Using Systems are Using System, using System.Collections.Generic.

Suppose in one other project we want to consume the Program Class then what we will do we just importing the “HellowWorldApp” namespace.

Main(): The main is a method which is an entry point of the program. When we run any program first the main method will execute even if other methods are present in our code.

void: It is a return type of method. Void means it does not return any value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}
c sharp tutorial
c#.net basic program

Solution Explorer: On the Right side of the IDE by default solution explorer we can see. The Solution explorer explores you the complete application in the other word it will show you the name of the solution under that what project are present under that what classes are present.

If you will not get the solution explorer in the visual studio right side section then we can find out from the View-> Solution Explorer.

Exploring Solution Explorer in Visual Studio

The Solution explorer contains below files.

Solution’HelloWorldApp'(1 project): In the top of the solution explorer we will see a solution file which is the top level of our solution. Always the Application contains a single solution file. Under a single solution file, we can create multiple projects. Microsoft provides the solution in VisualStudio just because organize the projects. While creating the project we are giving the location where we want to store our project. Go and check in the location the solution file name should be .sln extension for example “HelloWorldApp.sln”.

HelloWorldApp:
The HelloWorldApp is the project file which is present under Solution’HelloWorldApp’ solution. The project files contain source code, icon, data files, etc. The project files also contain some configuration and compiler settings page. We can only write the code in the source code of projects. The Projects file will save with the extension with .csproj like “HelloWorldApp.csproj”.

Properties:

Under the project one properties file is present. When we right click on the properties one property page will come where we can change the properties of the project. When we expand the Properties we can see AssemblyInfo.cs, file allows us to add the attribute to a program like “Title”, “description” and so on.

Reference: The visual studio by default will add some of the reference libraries which we can see when we expand the reference. We can add the reference manually and we can use the class method inside it.

App.config: The Application configuration file is optional, sometimes it is not visible in the solution explorer. This file allows us to change some settings such as a version of .net Framework.

DemoClass.cs: It is a source file contains the “DemoClass” which I have added manually. We will see later how to add a class in visual studio. This will come in one tab. If our visual studio contains more than one class we can toggle between the class.

Program.cs: This file will add automatically in the visual studio. This source file contains one Program class. The extension of the file is .cs.

visual studio solution explorer
visual studio solution explorer

We will see now how to print some message in the console application?

Now we will see how to I have written a message in a console application. Before knowing about how to write a message in console application we will what is Microso Intellisense.

We can display the message using “Console.WriteLine(“message”); “. So after the Main method { click on next then type Console.WriteLine(“Welcome to Tsinfotechnologies”). Microsoft provides the intelligence so that in the source file when we will type Con then automatically IntelliSense list will come we can click from the list otherwise we can type. The console is a predefined class.

visual studio c# console application
visual studio c# console application

After the Console Class when we put the “. “another IntelliSense will appear which contains methods, properties, and field of the Console class.

c sharp tutorial
visual studio c# console application

After WriteLine type “(” automatically closing brackeet will come. One red line is showing when we put the mouse on it it will show the error message that “;” expected. So the line end type “;”. Inside the WriteLIne method type the message with double quotation (“”).

visual studio c# console.writeline
visual studio c# console.writeline

Finally the code will look like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class Program
    {
        int cost= 10000;
        static int y = 2;

        static void Main(string[] args)
        {
           Console.WriteLine("Welcome to Tsinfotechnologies");
        }
    }
}

How to build and Run Console Application using Visual Studio 2017/2019

After we write the code in the source file now we will see how to build and run the console application using visual studio 2017 or visual studio 2019.

To build the Application click on Build from the top section of the Visual Studio IDE window. Then click on “Build Solution” otherwise we can click on “Ctrl+Shift+B“.

visual studio 2017 console application c#
visual studio 2017 console application c#

When we clicked on the build, the compiler will check the entire program line by line any error is there or not in the code. If our code is error-free in the output we can see the below screenshot otherwise we will get the error list instead of output.

how to run console application in visual studio 2017
how to run console application in visual studio 2017

Now to run the Application click on “Start without Debugging” or “Ctrl+F5“. If we have run the application by clicking on “Start Debugging” then command prompt will come but it will close suddenly without pressing any key.

c sharp tutorial
how to debug console application in visual studio 2017

The output window will look like below it will stay untill you donot press any key in the Keyboard.

visual studio 2017 console writeline output window
visual studio 2017 console writeline output window

Check Error Dusing Build in Console Application in Visual Studio

Suppose we did some mistake in our code then we will see the error message in a dialogue box. See what message is showing it is showing the code have some error do you like to run the last successful build. Means the last code will run. Click on No. Never ever check the “Do not show this dialog again”. If You will enable the checkbox then this dialog box will not come and directly the previous code will run.

visual studio c# console application
visual studio c# console application

In the button of the page, we can find the error list where all the error notification is present. We can check the error and rectify in our code.

c sharp tutorial
visual studio 2017 console application c#

We do not need to save the application. After the application builds successfully automatically it will save we will see now from where we can check the saved app.

Open the solution explorer click on the “HelloWorldApp” project then on the toolbar click on “Show All Files”. Now the bin and obj file will appear above the class name like Program.cs. the visual studio creates this folder after we build the application.

When we expand the bin we can see “HelloworldApp.exe” it’s an executable file or compiled file. The “exe” file will run when we clicked on Start without debugging.

visual studio bin and obj folders
visual studio bin and obj folders

Add a new class to Project in C#.Net using Visual Studio

Now we will see how to add a class in our program window. We will learn more about C#.Net class in another article. So to add a new class goes to Solution Explorer. Right click on the project. Click on Add->New Item.

how to create a class in c# visual studio 2017
how to create a class in c# visual studio 2017

Project is a collection of Item. By seeing the below Item list, we will know what is the item we can add in the projects. Choose the Class option. In the Button of page, by default one class name is present we can change the name otherwise we can use the default name. I have given a new name for the class. Click on Add button.

how to create a class in c# visual studio 2017
how to create a class in c# visual studio 2017

We can see in the below screenshot one solution is present. Under the solution one project is present and under the project, two class are present one is DemoClass.cs and Program.cs(default one).

how to add a c# class in visual studio 2017
how to add a c# class in visual studio 2017

In the Document Window we can see two class are present, we can toggle between the two classes.

c sharp tutorial
add class visual studio c#

When we clicked on the DemoClass.cs class page we can see all the using statement imported by default. We can also see the HelloWorldApp namespace this namespace is common for all the classes.

how to create a class in visual studio 2017
how to create a class in visual studio 2017

In the DemoClass I have written Console.WriteLine(“Welocme to SharePoint sky”). Now we will run the DemoClass click on Control+F5.

add class visual studio c#
add class visual studio c#

See one error is coming. Why this error now?

Because in two classes two main methods are present so two entry point for the project. The compiler gets confused which should run first and which should run second. So the error is coming.

c# multiple classes in one namespace
c# multiple classes in one namespace

So for that what we will do. Go to Solution Explorer. Right click on the Properties from the Solution Explorer. In the left side, one page will come. By default, the Application tab is opened if not then click on Application. We can see one field named a Startup object.

visual studio 2017 console application c#
visual studio 2017 console application c#

Choose the HelloWorldApp.DemoClass from the Startup object dropdown list and click on Control+F5.

visual studio 2017 console application c#
visual studio 2017 console application c#

The output will come like below screenshort.

visual studio 2017 console application c#.net
visual studio 2017 console application c#.net

Choose other class and click on Control+F5.

visual studio 2017 console application c#
visual studio 2017 console application c#

The second class output:

how to run the console application in c#
how to run the console application in c#

I have added one more class and named as TestClass.

how to create a class in visual studio 2017
how to create a class in visual studio 2017

We can see in the startup object new class is not available. Because the Class doesnot contains the main method.

run console application c#
run console application c#

Now I have added the Mian method in the Program window.

how to run the console application in c#
how to run the console application in c#

Go to the Properties. Now we will find the new class name in the Startup object.

run console application c#
run console application c#

C# .Net Identifier

C#.Net allows us to give the user-defined name for the program component such as class, interface, struct, enum, member, variable, namespace, etc is called identifier. When we are choosing the identifier name we should follow the below rule:

  1. We should start the identifier with a letter or underscore, we can not start with a number is not allowed.
  2. Remember that the C# is completely a case sensitive language. For example Cost and cost are different in C# .net.
  3. C#.net provide 77 reserved keyword we should not use that one as an identifier.
  4. The C#.net identifier cannot contain the letter more than 512.
  5. The Identifier is not allowed the white space like we can not give an identifier name as “cost value”.

Example of Identifier: “HelloWorldApp” is the identifier name for namespace. “DemoClass” is the identifier name for Class. The “productCost” is the identifier name for the variable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class DemoClass
    {
        static void Main(string[] args)
        {
            int productCost= 30;
   Console.WriteLine("Welcome to SharePoint sky");
        }
    }
}
what is identifier in c# with example
what is identifier in c# with example

C#.Net Keyword

C#.net have 78 reserved keyword which predefined identifier for its own use. All the keyword has some meaning for the compiler. We can not use the reserved keyword as an identifier. The keyword example is class, namespace and using.

  1. abstract
  2. as
  3. base
  4. bool
  5. break
  6. byte
  7. case
  8. catch
  9. char
  10. checked
  11. class
  12. const
  13. continue
  14. decimal
  15. default
  16. delegate
  17. do
  18. double
  19. else
  20. enum
  21. event
  22. explicit
  23. extern
  24. false
  25. finally
  26. fixed
  27. float
  28. for
  29. foreach
  30. goto
  31. if
  32. implicit
  33. in
  34. int
  35. interface
  36. internal
  37. is
  38. lock
  39. long
  40. namespace
  41. new
  42. null
  43. object
  44. operator
  45. out
  46. override
  47. params
  48. private
  49. protected
  50. public
  51. readonly
  52. ref
  53. return
  54. sbyte
  55. sealed
  56. short
  57. sizeof
  58. stackalloc
  59. static
  60. string
  61. struct
  62. switch
  63. this
  64. throw
  65. true
  66. try
  67. typeof
  68. uint
  69. ulong
  70. unchecked
  71. unsafe
  72. ushort
  73. using
  74. using static
  75. virtual
  76. void
  77. volatile
  78. while

In the code window all the keyword are coming in blue color. We can use the keywork as a identifier by using special character infront of it like @abstract. But its not a good practice to use the keyword name with special character.

Volatile keyword in C#.Net

Let us learn volatile keyword in C#.Net.

The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

The volatile modifier can be used only with the following types :

  • Any reference type.
  • Any pointer type.
  • The types sbyte, byte, short, ushort, int, uint, char, float, bool.
  • An enum type with an enum base type of byte, sbyte, short, ushort, int, or uint.

Example Code

using System;
using System.Threading;
class volatile_Test
{
   public static string result;
   public static volatile bool done;
   static void m1() {
      result = “This is sample data”;
      done = true;
   }
   static void Main() {
      done = false;
      // Run m1() in a new thread
      new Thread(new ThreadStart(m1)).Start();
      // Wait for m1 to signal that it has a result by setting
      // finished to true.
         if (done) {
            Console.WriteLine(“result = {0}”, result);
            return;
          }
   }
}

In this example, the method Main starts a new thread running the method m1. This method stores a string value into a non-volatile field called result, then stores truly in the volatile field done. The main thread waits for the field done to be set to true, then reads the string result. Since done has been declared volatile, the main thread must read the string “This is sample data” from the field result.

If the field has done had not been declared volatile, then it would be permissible for the store to result to be visible to the main thread after the store to do, and hence for the main thread to read the null value from the field result. Declaring done as a volatile field prevents any such inconsistency.

C#.Net Variable

Variable is the name of memory location used to store the value in our program. The Variable value can be changed and reusable many times. Variable is of a different type. Example:

Int age=20;

The Int is the type of variable, age is the variable name and assign the value 20.

C#.Net Variable Naming Convention

The naming convention is a set of rule that we should follow to declare a variable it will avoid confusion. Below is a set of rule which we should follow when declaring a variable.

  1. We should start the variable name in lower case.
  2. Remember when we have declared a variable with multiple keywords the first-word first letter should in lowercase and second-word first letter be in capital letter. This style is called camelCase notation for Example firstName.
  3. Always maintain one style for a variable declaration. In a program, if one variable is declared in camelCase notation then another variable should not declare in PascalCase notation.
  4. It’s not a good practice to start a variable name with underscore. It is allowed in C#.Net to use the underscore for the variable name but still not recommended.

Declare a variable in C#.Net

When we declare a variable we need to Declare the data type in c#.net. When we declare the variable we need to specify the type of data with a variable name. For Example “int cost;”. The int is the type of data and cost is the variable name. We must terminate the variable declaration with “;”. If we want to declare a variable for specific text then we can declare using the string name;”.

When declaring a variable we can not declare char first Name; . Space is not allowed. So we can declare char firstName;

Assign Value to Variable in C# .Net

After the variable declaration over we can assign the value to a variable. two styles we can assign value to a variable. The assigned value to a variable done using the “=”(assignment) operator.

int cost=100;//we can assign like this

int cost;

cost=100;

when we declare a character variable and assign a character value.

char name=”Alexa”;

Donot forget the semicolor in C# .Net.

We can not assign a string value to a integer variable like string x=2;

Access specifiers in C#.Net

Here we will see different access specifiers in C#.Net.

The accessibility determines whether other parts of your code will be able to read and alter this variable. This accessibility applies to variables, methods, properties, and events, etc.

public:
Can be accessed by any class.

private:
Can be accessed only by members inside the current class internal Can be accessed by members in any of the classes in the current assembly.

protected:
Can be accessed by members in the current class or in any class that inherits from this class.

protected internal:
Can be accessed by members in the current application (as with internal) and by the members in any class that inherits from this class.

Types of C#.Net Variables

There are following type of Variable in C#.Net

Static and Non static variable in C#.Net

If a Variable is explicitly declared by using the Static modifier then it is called a static variable. We can also call a variable as static if it declares inside a static block. Rest of the other variable is nonstatic variable.

In the below screen short int p=10; is a nonstatic variable. Static int y=2; is a static variable because to declare the variable the Static modifier is used. int Z=4; is also a static variable because it declares inside a Static block.

c# net static and nonstatic variable
c# net static and nonstatic variable

Suppose I want to pint the value of p and y. We can write a Console.WriteLine(y), but we can not write Console.WriteLine(p) because the memory for the p is going to be allocated only if you create an instance of a class. But y does not require an instance of the class. The static variable is initialized immediately once the execution of class start.

In the below example I am trying to print the static variable value. So I have written Console.WriteLine(y), so in the commandline, the y value is displaying.

c# instance variable
c# instance variable

But when we want to print the p value it will show the error. Here Instance is required for accessing the p value.

static variable in c#
static variable in c#

Whenever we are trying to consume a not static variable value from the static method we need to create an instance. In the below example I have created an instance that “Program P= new Program()”.

Now we can access the cost value like Console.WriteLine(P.Cost)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class Program
    {
        int cost= 10000;
        static int y = 2;

        static void Main(string[] args)
        {
            int Z = 4;
            Program P = new Program();
            Console.WriteLine(P.cost);
        }
    }
}

In the below screenshort we can see the output.

c# static variable example
c# static variable example

Read-only variable in C#.Net:If a variable is declared using the read-only keyword then we will call the variable as a read-only variable.

Constant variable in C#.Net: If the variable is declared using a const keyword it is called a constant variable. Once we declare the constant variable the value cannot be changed. When we declare a variable we must assign value to the variable in a constant variable. Otherwise, it will show the error. Because we can not assign the constant variable value in run time.

syntax of const float piVal=3.14f;// assign the value with f letter is compulsory. Because when we assign a piVal as 3.14 by default it works as a double value. All the decimal value treated as double. So need to mention as f so the compiler will know the value is float value.

Constants in C#.Net

Now, we will see C#.Net constants. A constant is a variable whose value cannot be changed throughout its lifetime. We have to use const keyword to declare a constant like below:

const int number = 10;

Some points to remember while working with constant:

  • They must be initialized when they are declared; and after a value has been assigned, it can never be overwritten.
  • The value of a constant must be computable at compile time. You can’t initialize a constant with a value taken from a variable. If you need to do this, you must use a read-only field
  • Constants are always implicitly static.

C#.net Data Types

Data type is the type of data that C#.net variable is holding. We can call the data type as a premptive data type. For example

Int cost=200;

Int is the data type, the cost is the variable name and assigns the 2 value to the variable. Basically, the data type informs the compiler what type of data the variable will hold.

C# Data type of 3 type

  1. Value Data Type
  2. Pointer Data Type
  3. Reference Data Type

Value Data Type: The Value Data type derived from System.ValueType. With the Value type variable, we can assign a value directly. Example: Integer is a value type variable. So we can assign the value to an integer variable.

Value Data Type is of 2 type

  1. Predefined Data Types
  2. Userdefined Data Types

The Predefined data type is that programing language natively support for example Integer, Float, Double etc.

The Value Data Type: The value data types are integer-based and floating-point based. C# language supports both signed and unsigned literals.

There are 2 types of value data type in C#.net language.

Predefined Data types are those that a programming language natively supports. It’s already defined in the library of the compiler. User cannot change or modify the predefined data type. For example Integer, Character, String, etc.

User-defined data type: These data types are created by the user as per user preference for example Structure, Enumeration, etc.

Pointer Data Type: The Pointer Type variable are used to store the address of another type. The Pointer data type is the same as pointer available in C and C++.

Example: char * StringName

Reference Data Type:

The Reference type variable does not contains the value of data, they contains reference to a variables.

Reference data type is of 2 type

  • Predefined: The Object, String is the built-in data type
  • User defined: The Class and interface is the User defined data type.

C# .net Implicitly Typed Local Variable

We will see now what is the Implicit type of local variable. In C#.net old version we need to declare a type of data when variable declaration. But in C# 3.0 introduce a new feature of Implicit type declaration.

Instead of int, char, string type we can use the var keyword. The var keyword will interfere in compile time from the initialization statement.

Example:

int price=200;//Explicit

var price=300;//Implicit

We should remember some point of explicit variable

  1. We should declare and initialize the variable at the same time. Example: var Price;//invalid. We need to assign the value var price=200;
  2. In the var keyword, we can not declare multiple variables in a single statement. Example: var price=100, color=”blue”, quantity=3; //invalid
  3. The var keyword we can not use in an expression like var price+=20;//invalid

Implicitely typed variables in C#.Net

It was a feature added in c#3.0 which allows declaring a variable using “var” keyword. The datatypes of the variable will be decided depending upon the value we assign to the variables.

We can not declare a variable using “var” without assigning a value. The “var” keyword may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library.

Multiple implicitly-typed variables cannot be initialized in the same statement.

Below are some examples:

// i is compiled as an integer
var i = 50;
// s is compiled as a string
var s = “aspdotnethelp”
// x is compiled as int[]
var x = new[] { 0, 1, 2 ,3};
// expr is compiled as IEnumerable<Customer>  or IQueryable<Customer>
var expr =
    from c in customers
    where c.Name == “AspDotNetHelp”
    select c;
// list is compiled as List<int>
var list = new List<int>();
// b is compiled as boolean
var b = false;
// anon is compiled as an anonymous type
var anon = new { Name = “Bijay”, Age = 31 };
// invalid
var=a;
Example:
Using System;
Class  ImplicitelyTyped
{
Static Void Main ()
{
Var  a = 200;
Console.WriteLine (a.GetType ());
Var  f = 3.14f;
Console.WriteLine (f.GetType ())
Var  s = “aspdotnethelp”;
Console.WriteLine (s.GetType ());
}
}

Output:
System.int32
System. Single
System. String

NOTE: GetType () is a predefined method which returns the type of given variable type or object.

C# Operator

The Operator in C#.net is a special symbol ask the compiler to do some mathematical and logical operation between the Operands. Based on the functionalities the Operator classified as follows type

Arithmetic Operator: The operator which preforms the arithmetic operation such as sum(+), Subtraction(-), division(/), modular devisison(%) and multiplication(*)

Relational operator: The combination of equal to(==), not equal to (!=), greater than(>), smaller than(<), greater than equal to(>=) and smaller than equal to(<=) operator are called C#.Net operator.

Logical Opearator: The Logic And(&&), Logic OR(||) and Logic Not(!) are the Logical Opearator.

Bitwise Opearator: bitwise And(&), bitwise Or(|), bitwise XOR(^), left shift(<<) ,right shift(>>) are bitwise opearator.

Assignment Opearator: simple assignment(=), add assignment(+=), substraction assignment (-=), multiply assignment(*=), division assignment(/=), modulus assignment(%=), left shift assignment(<<=), right sift assignment(>>=), BitwiseAnd assignment(&=), Bitwise Exclusive OR(^=) and Bitwise Inclusive OR(|=) are the assignment opearator.

Conditional Opearator: The ternary opearator is comes under Conditional Opearator.

Based upon the number of opearand the C# opearatore is of 3 type

Unary Operator: If one operand is present for the mathematical operation we called Unary Operator.

Example:++X

BInary Opearator: When two opearand are present to do one opearation is called Binary Opearator.

Example:X+Y;

Ternary Operator: The Operator syntax is “?:”. The ternary operator contains three operands.

Syntax:

Expression? If expression is true: if expression is false.

Static Keyword in C#.Net

A class in c sharp declared with the static keyword is a C# static class. The static class prevents the object creation and can be used directly without creating an instance of the class. A class that is not a static class is used after creating its object with the new keyword. But the class that is static is used directly without creating its object.

Create static class in c#.net

In order to create a static class in C#.net, you need to put static keyword before the name of the class as follow:

static class calculation
{
}
  • The static class can contain only static members.
  • The static class cannot be instantiated.
  • The static class is a sealed class so you cannot inherit and override its members.

Static Members in C#.Net

A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member.

Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state.

Example

using System;
namespace StaticKeywordConsoleApplication
{
static class calculation
{
public static int add(int num1, int num2)
{
return num1 + num2;
}
}

class Program
{
static void Main(string[] args)
{
int result;
result = calculation.add(6, 22);
Console.WriteLine(“Addition = ” + result);
}
}
}

Null Coalescing Operator in C#.Net

Now we will discuss C#.Net Null Coalescing operator.

This is a binary operator which is helpful in case of Null values evaluation and is noted as ??
Syntax:

A ?? B

Here it means if A is not null then evaluate A else take the value of Y.

Example:
int? i = null;
int j = a.Value;

Here in the 2nd statement, it will give an exception because we are trung to get the value which is null.
So to avoid the situation we can use Null Coalescing Operator

int? i = null;
int j = a ?? 0;

Here it will not give any exception rather it will take 0 and assign it to j.

If a is not null then it will evaluate an else it will take the value provided in Null Coalescing Operator which is 0 in this example.

Boxing and Unboxing in C#.Net

Now let us discuss on boxing and unboxing in C#.Net.

Boxing in C#.Net

Boxing is the process of transforming a value type to a reference type. Basically, the runtime creates a temporary reference-type box for the object on the heap.

This can happen explicitly or implicitly.

Example:

int number = 20;
object objNumber = number;

Here integer number which is value type is converted to object type which is a reference type.

Unboxing in C#.Net

Unboxing is the reverse process. Unboxing is the process of transforming a reference type to a value type.

But the reference type should be previously boxed. Here the value of a previously boxed value
type is cast back to a value type. And it should be done explicitly.

Here is a point to remember while doing unboxing: A variable can be unboxed only if it has been boxed.

int number = 10;
object objNumber = number; // Box the int
int number1 = (int)objNumber; // Unbox it back into an int

Special Operators in C#

C# supports following Eight Special Operators.

  • is: relational operator
  • as: relational operator
  • typeof type operator
  • sizeof: size operator
  • new: object creator
  • .(dot): member access operator
  • checked: overflow checking
  • unchecked: prevention of overflow checking

C#.Net Incrementing and Decrementing Variable

C#.net allows us to increment and decrement the variable. When we want to add 1 to a variable then we can use the + operator. First, assign the value to 10. Then increment the value by 1 and store in the value variable. Like that we can do the subtraction operation with “-” operator.

value=10;

value=value+1;

value=value++; is same as the value +1

C#.net Post Fix and Pre Fix Increment and Decrement opearator

PostFix Increment and Decrement Opearator:

We will know what is the prefix and post fix increment and decreement opearator.

int value=100;

Console.WriteLine(value); //The output is 100.

Console.WriteLine(value++); //The output is 100

Note: In the Post fix opearation first it will print the value then increment opearation will start.

Console.WriteLine(value);//the output value is 101. In the above statement, I did increment operation so now the value is 101.

For decrement

int age=20;

Console.WriteLine(age);// The output is 20.

Console.WriteLine(age–);//The output is 20

Console.WriteLine(age);//The output value is 19.

Prefix Increment and Decrement opearator:

int add=20;

Console.WriteLine(add);//20

Console.WriteLine(++add);//21

Here first the increment opearation is done then print the add value

Console.WriteLine(add);//21

Console.WriteLine(–add);//20

Console.WriteLine(add);//20

C# .net Opearator precidence

The Opearator precidence is the concept of order in which the opearator are executed.

For example:

int price=100;

int totalAvailable;

int totalPrice;

total=totalAvailable-price*Quantity;

Two operators are present now question is how it will be executed which operation will execute first the – or the * operation. The multiplication has high precedence so first multiplication operation will be executed when the – operation will execute.

Note: Some time two opearator have same precidence then how it will execute.

int price=10;

int total=10*50/2;

it will execute from the left side means first the multiplication operation will be done then the divide operation will be executed.

C# .net adding Parenthesis

We can change the order of precidence by using the parenthesis. The parenthesis has more precidence over all other operators.

Example: Suppose int price=100;

int total;

int quantity=9;

int totalAvailable;

total=totalAvailable-price*quantity;

So if we add the paranthesis toatl=(totalAvailable-price)*quantity

Now first the totalAvailable-price operation will be executed then the multiplication operation will be executed.

C#. Net Methods

In every C# .net program have at least one Main() method inside a class which is the entry point of the program. The methods are a combination of a collection of code, it will execute when the method is called. All method has some specific name make sure that the name is unique and meaningful.

By seeing the method name user should know what operation the method is performing. For example, “totalCost” is the method name. By seeing the method name we can easily know that the method is calculating the totalCost. The C# .net allows us to reuse the method again and again in our program, we just need to call the method by name.

How to Declare a Method in C#.Net?

Now we will see how to Declare a method in C#.Net.

The syntax of C#. net method is <Access Specifier><Return Type><Method Name>(Parameter List)

{

Method body or code to be executed

}

Access Specifier: The C#.Net provide 3 access modifier such as Public, Private and protected. It defined the methods of the access type. In the below code the access modifier is public.

Return Type: The return type defines the data type specified by the method. If our method does not have any return type then we should mention the void instead of the return type. In the below code our return type is an integer.

Method Name: The name should be meaningful. We should use the camelCase notation for declaring the method name. It is not a good way to add a special character between the name We can call the Method in a program by its name. In the below code the Method name is “totalProductPrice”.

Parameter List: The Parameter list is present between opening and closing parenthesis and separated from each other by a comma. This parameters list are optional. When no element is there in parenthesis we have to use empty parenthesis. The parameter list describes the type of data type with a variable name which we can pass through the method. Example: “int quantity” and “int productPrice”.

Method Body: The Method body is the code of statement and it will execute when we call the method name. The Method body starts with { and end with }.

Note:

  • We should write all the method inside a class. In my below code all the method are inside totalPrice Class.
  • The return type and parameter type we need to declare implicitly we can not declare explicitly means the var keyword is not allowed as a variable type.

The main method is “static void Main(string[] args)” is the entry point of C#.net.

namespace HelloWorldApp
{
    class totalPrice
    {
        static void Main(string[] args)
        {
            
        }
        public int totalProductPrice(int quantity, int productPrice)
        {
            /* local variable declaration */
            int totalPr;
            int qun = quantity;
            int prc = productPrice;
            totalPr= quantity * productPrice;
            return totalPr;
        }
    }
}

C#.Net Return Statement

Make sure that the return type and a return statement is of the same type. When we want to method return some information then we need to write the return statement. Like that when we do not want method write information we should mention the void type.

The statement which will come after the return statement that will not executed by the compiler.

When return type does not contain any type we can remove the Return Statement.

How to Call a method in C#.net?

Now we will see how to call a method by its name. when we call a method it will execute all the statement which is return inside the method body. We can reuse the method multiple time by its name.

We need to call the method in the Main method. Make sure that all method should be written inside the class.

First I have declared the Method inside the ” totalProductPrice ” method. Inside the “totalProductPrice” a bunch of code is present which is going to be executed when it is called.

In the totalProductPrice we have passed two parameters of integer type that is “int quantity” and another one is “int productPrice”.

Then I have taken two more variable “int qun” and “int prc”. In the qun store the quantity variable value and in the prc store the produtPrice value.

Then declare one more variable int “totalPr” and in that variable, I have done the mathematical operation. “that is “totalPr=quantity*productPrice”. At last, I have returned the return statement.

Now we will see how we call:

inside the Main method I have created a instance because the access modifier is of public in totalProductPrice method.

totalPrice tp = new totalPrice();

Assign the value to qun and prc variable.

Declare one more variable “totalProductCost” and then assign “tp.totalProductPrice(qun, prc);”// We call the method. Then in the Console.WriteLine I have print the value. To run the code click on control+F5.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class totalPrice
    {
        static void Main(string[] args)
        {
            totalPrice tp = new totalPrice();
            int qun = 12;
            int prc = 1000;
            int totalProductCost =tp.totalProductPrice(qun, prc);
           Console.WriteLine("The Total Price is"+" " +totalProductCost);
        }
        public int totalProductPrice(int quantity, int productPrice)
        {
            /* local variable declaration */
            int totalPr;
            int qun = quantity;
            int prc = productPrice;
            totalPr = quantity * productPrice;
            return totalPr;
        }
    }
}

The output screen will look like below:

how to call a method in c# console application
how to call a method in c# console application

Now we will see 3 example.

  1. No argument no return type
  2. Using argument and no return type
  3. Using Parameter and return type

C#.Net Method with no parameter and no return type

Below example I have taken a method with no argument and no return type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class NoArgumentNoReturnType
    {
        static void Main(string[] args)
        {
            NoArgumentNoReturnType noParameterAndReturnTypeObj = new NoArgumentNoReturnType();
            noParameterAndReturnTypeObj.displayMessage();
        }
        public void displayMessage()
        {
            Console.WriteLine("The Message is typed with no argument and no return type");
        }
    }
}
function with no argument and no return value
function with no argument and no return value

C#.Net methods with Argument and no return type

Below is the C#.Net method example having an argument but with no return type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class uingParameterNoReturnType
    {
        public void add(int price,int quan)
        {
            int totalPrice = price * quan;
            Console.WriteLine("The total Price is"+" "+totalPrice);
             
        }
        static void Main(string[] args)
        {
            uingParameterNoReturnType useParameterNoParameterObj = new uingParameterNoReturnType();
            useParameterNoParameterObj.add(23, 2);
                 
        }
    }
}
function with argument and no return value in C#
function with argument and no return value in C#

What ever I have took the code in how to call a method that one is using argument and parameter.

Method Overriding in C#.Net

Two methods having the same name(method definition) and same signature(parameter) but different class one is base class other one is derived class is called Method Overriding in C#.Net.

In the below example electronicsProduct is a derived class of Product class.

We will see now what is C#.Net method overriding?

class Product: It is a base class.

static void Main(string[] args): Method Declaration. It is a main method entry point for the program. Everyprogram should contains atleast one Main().

electronicsProduct ep = new electronicsProduct(): Create an instance for child class. The electronicsProduct is a child class.

int qun = 12: and int prc = 1000: Assign value to qun and prc.

int totalProductCost = ep.totalProductPrice(qun, prc): Declare a variable totalProductCost then call the totalProductPrice method of child class and pass the qun and prc value as a parameter. ep is the instance. In nonstatic modifier we can not access a method with out creating a instance.This method is classic but from where we are calling the method that is non static so instance is required.

Console.WriteLine(“After Discount The Price is” + ” ” + totalProductCost): Print the totalProductCost value with some message.

Now we will see in the same class how to call the base class method.

Product pr = new Product(): Create one more instance for base class.

int totalProductPr = pr.totalProductPrice(qun, prc):Create one more variable and call the base class method. Pass the qun and prc variable.

Console.WriteLine(“The total price is” + ” ” + totalProductPr): Print the message with totalProductPr value.

public virtual int totalProductPrice(int quantity, int productPrice): Method Declaration of base class. Virtual methods in C#.Net.

int totalPr;int qun = quantity;int prc = productPrice;totalPr = quantity * productPrice;return totalPr:Method body of base class

class electronicsProduct:Product: The electronicsProduct is a child class of Product class.

public override int totalProductPrice(int quantity, int productPrice): Child class method declaration. Make sure that donot forget to use override keyword.

int totalPr;
int qun = quantity;
int prc = productPrice;
int dis = 200;
totalPr = quantity * productPrice*(dis/100);
return totalPr: Method body of child class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class Product
    {
        static void Main(string[] args)
        {
            electronicsProduct ep = new electronicsProduct();
            int qun = 12;
            int prc = 1000;
            int totalProductCost = ep.totalProductPrice(qun, prc);
            Console.WriteLine("After Discount The Price is" + " " + totalProductCost);
            Product pr = new Product();
            int totalProductPr = pr.totalProductPrice(qun, prc);
            Console.WriteLine("The total price is" + " " + totalProductPr);
        }
        public virtual int totalProductPrice(int quantity, int productPrice)
        {
            /* local variable declaration */
            int totalPr;
            int qun = quantity;
            int prc = productPrice;
            totalPr = quantity * productPrice;
            return totalPr;
        }

    }
    class electronicsProduct:Product
    {
        public override int totalProductPrice(int quantity, int productPrice)
        {
            /* local variable declaration */
            int totalPr;
            int qun = quantity;
            int prc = productPrice;
            int dis = 200;
            totalPr = quantity * productPrice*(dis/100);
            return totalPr;
        }

    }
}

The output is:

c sharp tutorial
c# method overriding example

C#.Net Method Overloading

When we are using more than one method with the same method name and a different number of the parameter is called Method Overloading in C#.net.

We can perform the method overloading in different way.

  1. Change the Number of the parameter in 3 method
  2. The different Data type of the parameter in a method

Change the Number of parameter in 3 method of same method name:

In the below example we can see I have created 3 methods except for the main method the method name is same but a number of parameters are different.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class geometricFigurePerimeter
    {
        static void Main(string[] args)
        {
            geometricFigurePerimeter gfp = new geometricFigurePerimeter();
            int b = 18;
            int h = 6;
            int rectPerimeter = gfp.perimeter(b, h);
            Console.WriteLine("The Perimeter of rectangle is" + " " + rectPerimeter);
            int b1 = 10;
            int b2 = 5;
            int b3 = 12;
            int tringPerimeter = gfp.perimeter(b1, b2, b3);
            Console.WriteLine("The Perimeter of tringle is " + " " + tringPerimeter);
            int r = 20;
            int circlePerimeter = gfp.perimeter(r);
            Console.WriteLine("The Circle perimeter is " + "" + circlePerimeter);
        }
        public int perimeter(int rectBase, int rectHeight)
        {
            int b = rectBase;
            int h = rectHeight;
            int rectPerimeter = 2*(rectBase+ rectHeight);
            return rectPerimeter;
        }
        public int perimeter(int triB1,int triB2,int triB3)
        {
            int b1 = triB1;
            int b2 = triB2;
            int b3 = triB3;
            int triPerimeter = triB1 + triB2 + triB3;
            return triPerimeter;
        }
        public int perimeter(int radius)
        {
            int r = radius;
            int squarePerimeter = 4 * radius;
            return squarePerimeter;
        }
    };
}

Output: The out put will look like below screenshort

c# method overloading example
c# method overloading example

The different Data type of the parameter in a method:

In the below example we will see when we will pass different type of argument in method overloading. Two method are differentiated from each other based on the argument data type. In one method we are passing two integer value. And in the other mathod we have passed the float type and integer type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class AreaOfGeometricalShape
    {
        static void Main(string[] args)
        {
            AreaOfGeometricalShape areaObj = new AreaOfGeometricalShape();
            int b = 12;
            int h = 3;
            int areaRectangle = areaObj.Area(b, h);
            Console.WriteLine("The Area of rectangle in integer is"+" "+areaRectangle);
            float bas = 1.2f;
            int height = 6;
            float area = areaObj.Area(bas, height);
            Console.WriteLine("The Area of rectangle in float is"+" "+area);
        }
           public int Area(int rectBase, int rectHeight)
        {
            int b = rectBase;
            int h = rectHeight;
            int rectangleArea = rectBase * rectHeight;
            return rectangleArea;
        }
        public float Area(float rectBase, int rectHeight)
        {
            float bas= rectBase;
            int hght= rectHeight;
            float rectangleArea = rectBase * rectHeight;
            return rectangleArea;
        }

    }
}

Output: In the output screen we can see one value in integer and another value in float value.

method overloading in c# with example
method overloading in c# with example

C#.Net Function Call By Value

In the .Net framework in the method or function when we pass the value as a parameter or argument we called as call by value. In the Call By value, we are calling the function by its variable name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class callByValue
    {
        public void leftProduct(int totalProduct, int broughtProduct)
        {
            int productLeft;
            int p1 = totalProduct;
            int p2 = broughtProduct;
            productLeft = totalProduct - broughtProduct;
            Console.WriteLine("The Product Left is"+" "+productLeft);
        }
        static void Main(string[] args)
        {
            int p1=1000;
            int p2 = 400;
            callByValue callByValueObj= new callByValue();
            callByValueObj.leftProduct(p1, p2);
           
        }
    }
}
C#.net call by value
C#.net call by value

C#.Net Function Call By Reference

In the C#.net when we call the function through the reference of variable we called as Call By reference.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class CallByReference
    {
        static void Main(string[]args)
        {
            int cost= 200;
            Console.WriteLine("Before calling the cost value is:" + " " + cost);
            CallByReference callByReferenceObj = new CallByReference();
            callByReferenceObj.display(ref cost);
            Console.WriteLine("Now the price value is" + "" + cost);
        }
        public void display(ref int price)
        {
            price *= price;
            Console.WriteLine("Inside the display method the price value is" + " "+price);
        }
    }
}
c#.net call by reference
c#.net call by reference

Passing Parameter By Output:

When we call the method using the out keyword. The Passing Parameter by output is useful when a method returns more than a value. The out parameter we can pass without declaration and initialize of a variable. When we have worked on a passing parameter by output the variable initialization is not required before passing the variable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class PassingParameterByOutput
    {
        static void Main(string[] args)
        {
            PassingParameterByOutput passingParameterByOutputObj = new PassingParameterByOutput();
            int costPrice = 100;
            Console.WriteLine("Before the method called the cost is" +" "+costPrice);
            passingParameterByOutputObj.calculation(out costPrice);
            Console.WriteLine("After the method call the cost is" + " " + costPrice);
        }
        public void calculation(out int cost)
        {
            int newCost = 1000;
            cost = newCost;
        }
    }
}

The output screen will look like below

call by reference in c# example
call by reference in c# example

C#.Net Conditional Statement

A block of code will be executed when the condition is executed to true is called a conditional statement. The conditional statement is of below type.

  1. If statement
  2. if-Else statement
  3. If-else-if
  4. Nested if else

In the below example it will take the input from the user. So for that the Console.ReadLine() method is used. But the return type of this method is String. To convert to a integer value int.Parse method is used. The Parse method is used to convert string to numeric like int,lonng ,double etc.

If-Statement in C#.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class IfStatement
    {
        public static void Main(string[] args)
        {
            int age;
            Console.WriteLine("Enter the age:");
            age= int.Parse(Console.ReadLine());
            if (age > 18)
            {
             Console.Write("Elligible For Voating \n");
            }
        }
    }
}
conditional statements in c# with example
conditional statements in c# with example

If-Else Statement in C#.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class IfElse
    {
        public static void Main(string[] args)
        {
            int age;
            Console.WriteLine("Enter a age");
            age = Convert.ToInt32(Console.ReadLine());
            if (age < 18)
            {
                Console.WriteLine("Not elligible for vote");
            }
            else
            {
                Console.WriteLine("Elligible for voting");
            }

        }
    }
}
c# if and else statement
c# if and else statement
if else statement in c# example
if else statement in c# example

if-else-if Statement in C#.Net

In the below example I have taken one if else if statement which will show the description of grade when you will put the grade.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorldApp
{
    class NestedIfElse
    {
        public static void Main(string[] args)
        {
            String Grade;
            Console.WriteLine("Enter Your Grade");//
            Grade =Convert.ToString(Console.ReadLine());
            if (Grade == "O")
            {
                Console.WriteLine("OutStanding");
            }
            else if (Grade == "E")
            {
                Console.WriteLine("Excellent");
            }
            else if (Grade == "A")
            {
                Console.WriteLine("Very Good");
            }
            else if (Grade == "B")
            {
                Console.WriteLine("Good");
            }
            else if (Grade == "C")
            {
                Console.WriteLine("Fair");
            }
            else if (Grade == "D")
            {
                Console.WriteLine("Below Average");
            }
            else if (Grade == "F")
            {
                Console.WriteLine("Fail");
            }
            
        }
    }
}
c# if else if example
c# if else if example
c# if statement multiple conditions
c# if statement multiple conditions

Nested If Else Statement in C#.Net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicSolution
{
    class Program
    {
        static void Main(string[] args)
        {
            int age;
            Console.WriteLine("Enter Your Age");
            age = Convert.ToInt32(Console.ReadLine());
            if(age>14)
            {
                if(age>18)
                {
                    Console.WriteLine("Audult");
                }
                else
                {
                    Console.WriteLine("TeenAge");
                }
            }
            else
            {
                if (age > 0)
                {
                    Console.WriteLine("Child");
                }
                else {
                    Console.WriteLine("Something Wrong");
                    }
                
            }
        }
    }
}
C# nested if else
C# nested if else
nested if statements in c#
nested if statements in c#
c# nested if statements
c# nested if statements

The ternary Opearator for conditional statement in C#.Net

The ternary Opearator will work like if else statement.

The Syntax is

Statement1/Condition?Statement2:Statement3

When the Statement1 is true then the Statement2 will execute. The Statement3 will execute when Statement 1 is false.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicSolution
{
    class Tearnary
    {
        static void Main(string[] args)
        {
            int age;
            Console.WriteLine("Enter age");
            age =Convert.ToInt32(Console.ReadLine());
            Console.WriteLine(age > 18 ? "elligible for vote" : "Not Elligible for vote");
        }
    }
}
c#.net ternary operator example
c#.net ternary operator example
c# ternary operator
c# ternary operator

Switch Statement in C#.net

The Switch statement is like an if-else-if ladder. The switch statement will execute the code when the expression value is true.

switch statement that you can use to evaluate a single variable or expression for multiple possible values.

switch statement supports only an integer-based data type, a bool, a char, a string, or a value from an enumeration. Other data types aren’t supported.

Each case statement should end with a break; statement else compiler will give an error. But if a case statement does not contain any code then it may not contain a break statement.

Syntax:

switch(expression)
{
case value1:code to be executed;
break;
case value2:code to be executed
break;
case valueN:code to be execute
breate;
default://optional
code to be executed;
break;
}

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicSolution
{
    class Switch
    {
        static void Main(string[] args)
        {
            int monthNumber;
            Console.WriteLine("Enter the month Number");
            monthNumber = Convert.ToInt32(Console.ReadLine());
            switch (monthNumber)
            {
                case 1:
                    Console.WriteLine("January");
                    break;
                case 2:
                    Console.WriteLine("February");
                    break;
                case 3:
                    Console.WriteLine("March");
                    break;
                case 4:
                    Console.WriteLine("April");
                    break;
                case 5:
                    Console.WriteLine("May");
                    break;
                case 6:
                    Console.WriteLine("June");
                    break;
                case 7:
                    Console.WriteLine("July");
                    break;
                case 8:
                    Console.WriteLine("Augest");
                    break;
                case 9:
                    Console.WriteLine("September");
                    break;
                case 10:
                    Console.WriteLine("Octobar");
                    break;
                case 11:
                    Console.WriteLine("November");
                    break;
                case 12:
                    Console.WriteLine("December");
                    break;
            }
        }
    }
}

The output screen will look like below, when we entered 5 then the May is showing.

c# net switch case example
c# net switch case example

Switch Statement Rules in c#.net

We will discuss what are the rules we need to follow while writing a switch case.

The switch statement is very useful, but unfortunately, you can’t always use it when you may like to. Any switch statement you write must follow to the following rules:

You can use switch only on primitive data types, such as int or string. With any other types (including float and double), you’ll have to use an if statement.

The case labels must be constant expressions, such as 42 or “42”. If you need to calculate your case label values at runtime, you must use an if statement.

The case labels must be unique expressions. In other words, two case labels cannot have the same value.

You can specify that you want to run the same statements for more than one value by providing a list of case labels and no intervening statements, in which case the code for the final label in the list is executed for all cases in that list. However, if a label has one or more associated statements, execution cannot fall through to subsequent labels, and the compiler generates an error.

For example:

switch (xyz)
{
case hey :
case bye :
color = “Red”;
break;
case Clubs :
color = “Black”;
case Spades :
color = “Black”;
break;
}

C#.Net Loops

Here we will discuss on loops in c#.net.

ForLoop in C#.Net

The “for” keyword is used to create a for loop in C#.Net. The for loop is preferred when the number of iteration is fixed. First, we will initialize the variable in the for a loop. Then we will check for the condition, is the condition is true or not. If the condition is true the then the block of code will execute. Then the variable value will increment or decrement. When the condition will false then it will come out from the loop.

Syntax:

for(Initialization;Condition;increment/decrement)
{
block of code to be execute
}

Sum of n natural number:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicSolution
{
    class FoorLoop
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a num value");
            int num = Convert.ToInt32(Console.ReadLine());
            int count;
            int sum = 0;
            for(count=1;count<=num;count++)
            {
                sum = sum + count;
            }
            Console.WriteLine("The Sum value of "+ num +" natural number is"+" "+ sum);

        }
    }
}
C# for loop
C# for loop

While-Loop in C#.Net

The while loop will be executed until the condition is satisfied. When the condition is false it will come out from the loop and the code will execute which is outside of the loop. If the number of iteration is not fixed it is preferred to go for while loop.

Syntax:

While(Condition)
{
Execute a block of code
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicSolution
{
    class WhileLoop
    {
       static void Main(string[] args)
        {
            Console.WriteLine("Enter a Number");
            int num = int.Parse(Console.ReadLine());
            int sum = 0;
            int count = 1;
            while(count<num)
            {
                sum = sum + count;
                count++;
            }
            Console.WriteLine("The Sum value of "+ num +" is"+ " " +sum);
        }
    }
}
C# while loop
C# while loop

Do-While Loop in C#.Net

The do-while loop is similar to while loop but the only difference is the condition will evaluate the end of the program. At least once the code will execute then it will go for the check condition. The do block contains the code to be executed and in while loop the condition is present. When the number of iteration is not fixed and we need to execute the loop once then we can go for the Do-While Loop.

Syntax:

do
{
Statements..
}
whiile(Condition to be evaluted);

Example: Sum Of N natural number using C#.Net Do-While Loop

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the number");
            int num = int.Parse(Console.ReadLine());
            int count = 1;
            int sum = 0;
            do
            {
                sum = sum + count;
                count++;
            }
            while (count < num);
            Console.WriteLine(sum);
        }
    }
}

The output screen will look like below. In the output command prompt it will asking for enter a number. Then add one number. I have entered 5,so output is coming as 10.

c#.net do while loop
c#.net do while loop

What is an array of C#.Net?

C#.Net allow an array concept which allows us to store more than one value of the same data type in a single variable. Like “int cost=100;”. In the cost variable, we could not store more value. But using array concept we can store more than one value in a single variable.

Sometimes our business requirement will come to store more than 100 number of the same data type. In that situation, we need to declare all the 100 number with different variables. It’s a hectic process. Instead of declaring 100 variable for 100 value we can declare a variable using array and store 100 value.

The array index starts from 0 value. C# provides a special syntax for array declaration, array initialization and how to access the array in our program. We are declaring the array with the common name then using the name and passing the index value we can access the value.

Declare an array using C#.net

For using an Array first we need to declare an Array in our program. The following syntatical rule we need to follow for array declaration.

Syntax: data type[] arrayName;

data type[]: It specifies the type of element the array store. Suppose “int” means the array contains all the int value.

[]: The [] defines the size of arry or length of array.

arrayName: We need to give one name for array.

Example:

string[] empName;

Initialize an array using C#.Net

After the Array declaration over, we need to initialize the array. The initialization is defined as how many array element the array is holding with []. The array is reference type so for an array initialization, the new keyword is used.

Syntax:

datatype[] arrayname=new datatype [size];

Example:

string[] empName=new string[10];// The Size of array is 10.

Assign Value to array in C#.Net

After array declaration and initialization we need to assign value to array.

Example: In the following way we can assign value to array.

In the below example I have created an empName array of type string and we have assigned some of the value in that. In the below 3 way we can assign value to an array.

1. string[] empName = new string[3] { "Padmini", "Preeti", "Lakshmi" };
2. string[] empName= new string[]{"Padmini","Preeti","Lakshmi"};
3. string[] empName={"Padmini","Preeti","Lakshmi"};

Access the Array element in C#.Net

We can access the array using empName[1]

Now we will see how to access the Array element.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicProgram
{
    class ArrayBasic
    {
        static void Main(string[] args)
        {
            string[] empName = new string[3] { "Padmini", "Preeti", "Lakshmi" };
            Console.WriteLine(empName[1]);
           for (int i = 0; i < empName.Length; i++)
            {
                Console.WriteLine(empName[i]);
            }
        }
    }
}

Output:

C# array
C# array

Use For Each loop to access an array element

Here I am using the for ech loop to accessin the array element.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicProgram
{
    class ArrayBasic
    {
        static void Main(string[] args)
        {
            string[] empName = new string[3] { "Padmini", "Preeti", "Lakshmi" };
            Console.WriteLine(empName[1]);

           
            foreach (string name in empName)
            {
                Console.WriteLine(name);
            }
        }
    }
}

Output: The Output screen will look like below.

c# foreach loop
c# foreach loop

The Array is of 3 types

  1. One Dimensional Array
  2. Multi Dimensional Array
  3. Jagged Array

One Dimensional Array in C#.Net

The One Dimensional Array also called as Single Dimensional array. The single dimensional array has only one row for storing the data of homogeneous data type.

For example :

int[] price=new int[4];

That Means the size of the array is 0 to 3 is 4 element. Each item of the array represent as price[0], price[1], price[2], price[3].

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicProgram
{
    class OneDiemsion
    {
        static void Main(string[] args)
        {
            int[] priceCost = new int[] { 100, 1200, 13000, 800, 900, 300 };
           foreach(int price in priceCost)
            {
                Console.WriteLine("the price is" + "" + price);
            }
           
        }
    }
}

Output:

one dimensional array in c#
one dimensional array in c#

Multi-Dimensional Array in C#.Net

We called the array a Multi-Dimensional Array when it has more than one row. The Multi-Dimensional array can be 2 dimensional or 3 dimensional or more than that. The multidimensional structure looks like a matrix structure. Example of a multidimensional array having 3 row and 4 columns.

 int[,] price=new int[3,4];
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicSolution
{
    class twoDimensional
    {
        static void Main(string[] args)
        {
           
            int[,] marks= new int[5, 3] { { 12,29,70 }, { 100, 28,56 }, { 82, 44,88 }, { 93, 86,39 }, { 34, 48,54 } };
            int i, j;

            
            for (i = 0; i < 5; i++)
            {

                for (j = 0; j < 3; j++)
                {
                    Console.WriteLine("marks[{0},{1}] = {2}", i, j, marks[i, j]);
                }
            }
            Console.ReadKey();
        }
    }
}
multidimensional array in c#
multidimensional array in c#

C#.Net Jagged Array

Now we will see what is a jagged array in C#.net. The jagged array is the array of array. That means the element of the jagged array is an array. The jagged array element can be a different dimension and different size. We will see now how to declare, initialize and access the jagged array in C#.Net.

In the following example, we declare a jagged array which is of single dimension array contains 4 elements of string type. Each element of the array is of single dimension of string type.

string[] jaggedArray=new string[4][];//declaration
jaggedArray[0] = new string[] { "String","Riya","Bijay","Lakshmi","Saroj","Asok" };
jaggedArray[1] = new string [] {"Padmini Kumari","Preeti"};
jaggedArray[2] = new string[] { "Padmini","Preeti" };
jaggedArray[3] =new string[]{"Mama","Preeti","Swati"}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicsArrayString
{
    class Program
    {
        static void Main(string[] args)
        {
            string[][] jaggedArray = new string[3][];

            // Initialize the elements:
            jaggedArray[0] = new string[3] { "Padmini","Preeti","Lakshmi" };
            jaggedArray[1] = new string[2] {"Microsoft","Google"};
            jaggedArray[2] = new string[2] { "IBM", "TCS" };

            // Display the array elements:
            for (int i = 0; i < jaggedArray.Length; i++)
            {
                Console.Write("JaggedArray({0}): ", i);

                for (int j = 0; j < jaggedArray[i].Length; j++)
                {
                  Console.Write("{0}{1}", jaggedArray[i][j], j == (jaggedArray[i].Length - 1) ? "" : " ");
                }
               Console.WriteLine();
            }
            
        }
    }
}

Output:

c#.net jagged array example
c#.net jagged array example

Jagged arrays in C#.Net:

A jagged array is an array where every row can have different size, a jagged array is very much flexible in sizing. Means the first row can have 5 elements, the 2nd row can have 4 elements, the 3rd row can have 10 elements etc.

It is also called an array of arrays.

Below is a a single-dimensional integer array that has three elements.

int[][] jaggedArray = new int[3][];

And then you can define the elements for each row like below:

jaggedArray[0] = new int[3];
jaggedArray[1] = new int[2];
jaggedArray[2] = new int[5];

Here the first row will contain 3 elements, the 2nd row will contain 2 elements and the 3rd row will contain 5 elements.

Then you can initialize the value to the row like below:

jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9, 10, 11 };

C#.Net enum

The Enum keyword is used to defines a set of constant value in the program. The constant is called the enumerator. The enum keyword starts from 0 and increments one by one.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class EnumExam
    {
        enum Grade { Outstanding,Excellent,Average,BelowAverage,Fail }
        static void Main(string[] args)
        {
            int outstndng = (int)Grade.Outstanding;
            int fail = (int)Grade.Fail;
            Console.WriteLine("Outstanding= {0}", outstndng);
            Console.WriteLine("Fail = {0}", fail);
        }
    }
    
}
c# enum keyword
c# enum keyword

C#.net String

The String is a data type like character data type. But the difference between the character and string is the character data type is used for single letter where as the string is used for more than one letter. For example char firstLetter = ‘P’; and for string is string firstName = “Padmini”;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicsArrayString
{
    class CSharpString
    {
        static void Main(string[] args)
        {
            string firstName = "Padmini Kumari";
            string education = "Graduate";
            string workingStatus = "Working";
            Console.WriteLine(firstName);
            Console.WriteLine(education);
            Console.WriteLine(workingStatus);
        
        }
    }
}
string-in-c#
string-in-c#

C#.Net String Method

Clone(): The Clone method is used to return a copy of same data. In the below example in the orgName variable of string type I have stored “Tsinfotechnology” and declare one more variable of string type as orgNameRep and store the clone value of variable1. In the console. writeline I have printed both the variable value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicsArrayString
{
    class CSharpString
    {
        static void Main(string[] args)
        {
           string orgName = "Tsinfotechnologies";
            string orgNameRep = (string)orgName.Clone();
            Console.WriteLine(orgName);
            Console.WriteLine(orgNameRep);
        }

    }

}
c# clone
c# clone

Compare(): The Compare method is used to compare two string lexicographically. Compare(String1, String2), if String1 and String2 are equal then the output will come 0. If the string1 is greater then string2 then 1 will come in output. If the output will come -1 that means the string2 is greater then string1.

Example-1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string sub1 = "Physics";
            string sub2 = "Chemestry";
            string sub3 = "Mathmatics";
            string sub4 = "Physics";
            Console.WriteLine(string.Compare(sub1, sub2));
            Console.WriteLine(string.Compare(sub1, sub4));
            Console.WriteLine(string.Compare(sub2, sub1));
            
        }
    }
}
c# compare strings greater than
c# compare strings greater than

Example-2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class Program
    {
        static void Main(string[] args)
        {
            string sub1 = "Physics";
            string sub2 = "Chemestry";
            string sub3 = "Mathmatics";
            string sub4 = "Physics";
            if(string.Compare(sub1, sub2)==1)
            {
                Console.WriteLine("The Sub1 is greater then Sub2");
            }
            else
            {
                Console.WriteLine("The Sub2 is greater then sub1");
            }
            if(string.Compare(sub2,sub1)==1)
            {
                Console.WriteLine("The Sub2 is greater then sub1");
            }
            else
            {
                Console.WriteLine("The sub1 is greater then sub2");
            }
            if(string.Compare(sub1,sub4)==0)
            {
                Console.WriteLine("The sub1 and sub4 is equal");
            }
            else
            {
                Console.WriteLine("The sub1 and sub4 is not equal");
            }
        }
    }
}
string.compareto c#
string.compareto c#

Concat():

The Concat() method is used to concatenate more then one string object and showing in a single line.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class StringConcat
    {
        static void Main(string[] args)
        {
            string Author = "Binaya";
            string Domain = "SharePoint Devloper";
            string WorkingExperience = "15 Year";
            Console.WriteLine(string.Concat(Author," " ,Domain," " ,"having experience ", WorkingExperience));
        }
    }
}
c#-.net-string-concatenation
c#-.net-string-concatenation

Contains():

The Contains() method will check is the substring occurs within this string or not. The Contains() method return in boolean value in true and false.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class StringContains
    {
        static void Main(string[] args)
        {
            string str1 = "C sharp programing";
            string str2 = "C sharp";
            if (str1.Contains(str2))
            {
                Console.WriteLine("Yes it contains");

            }
            else
            {
                Console.WriteLine("Not contains");
            }
        } 
    }
}
c# string contains character
c# string contains character

Trim(): The String trim method is used to remove the space and white space character from leading and trailing of string. The Trim() returns a string value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class StringTrim
    {
        static void Main(string[] args)
        {
            string csharp = "  CSharp ";
            string cbasics = "    CSharpBasicProgramming  ";
            Console.WriteLine(cbasics);
            Console.WriteLine(csharp);
            Console.WriteLine(csharp.Trim());
            Console.WriteLine(cbasics.Trim());
           
        }
    }
}
c# trim characters
c# trim characters

Trim Start() and TrimEnd():

The TrimStart() method is used to remove the set of character from the starting of the current string object. The TrimEnd() method is used to remove the set of character from the end of the string object. Both the Trim start and TrimEnd return the string value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class trimstartandtrimend
    {
        static void Main(string[] args)
        {
            string countryName = "IndiaCapitalisDelhiI";
            char[] trimLetter = { 'I' };
           Console.WriteLine(countryName.TrimEnd(trimLetter));
            string cityName = "ABenguluru";
            char[] trimlet = { 'A' };
            Console.WriteLine(cityName.TrimStart(trimlet));
        }
    }
}
c# string trimstart
c# string trimstart

ToUpper() and ToLower():

The ToUpper() and ToLower() method is used to convert the string in UpperCase and LowerCase respectively. both ToUpper() and ToLower() returns in a string value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class StringToUpperAndLower
    {
        static void Main(string[] args)
        {
            string stateName = "karnataka";
            string Uppstatename = stateName.ToUpper();
            string Lowstatename = stateName.ToLower();
            Console.WriteLine(Uppstatename);
            Console.WriteLine(Lowstatename);
        }
    }
}
c sharp tutorial
c# string case

ToString(): It is used to convert the value to string type.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class ToString
    {
        static void Main(string[] args)
        {
            int mark = 90;
            Console.WriteLine(mark.ToString());
        }
    }
}
c# .net tostring
c# .net tostring

Equals(): The Equals() method is used to check whether the two specified string have the same value or not. If the value is same then it will show true and if not false will display.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class EqualTo
    {
        static void Main(string[] args)
        {
            string state1= "Karnataka";
            string state2 = "Andhrapradesh";
            string state3 = "Karnataka";
            Console.WriteLine(state1.Equals(state2));
            Console.WriteLine(state1.Equals(state3));
        }
        
    }
}

Join():

The Join() is a string method which is used to concatenate the array element, by using separate separator between the items.

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class Join
    {
        static void Main(string[] args)
        {
            int[] marks = {100,90,80,70};
            
            Console.WriteLine(string.Join("/",marks));
        }
    }
}
c sharp tutorial
string.join c#

Format():

The Format() method is used to convert a string format into a desired format.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class formatmethod
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("Now the time is {0:d} and time is {0:t}", DateTime.Now));
        }
    }
         
}
c# string format date
c# string format date

Insert():

The C# String Insert() method is used to insert a specified string in the specified number. The method will return the modified string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class Insert
    {
        static void Main(string[] args)
        {
            string empName = "MonohorPariker";
            Console.WriteLine(empName.Insert(7, "-"));
        }
    }
}
c# insert method
c# insert method

GetType and GetTypeCode:

The C# string GetType() method is used to get the type of current object, it returns an object of type class.
Like that the GetTypeCode() method used to get the type of current object, it does not return the type class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class GetType
    {
        static void Main(string[] args)
        {
            int marks= 200;
            Console.WriteLine(marks.GetType());
            Console.WriteLine(marks.GetTypeCode());
        }
       
    }
}

Output;

c# gettype method
c# gettype method

IndexOf():

The C# string IndexOf() method is used to get the index of specified character from the string. The method will return in an integer value.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class IndexOf
    {
        static void Main(string[] args)
        {
            string compName= "Tsinfotechnologies is a IT devlopement organization";
            Console.WriteLine("The f letter position in Tsinfotechnologies is "+compName.IndexOf('f'));
        }
    }
}
C# index of method
C# index of method

IsNullOrEmpty():

C# string IsNullOrEmpty() method is used to check weather the variable contains null value or whitespace or not. The return type of IsNullOrEmpty method is in boolean either in true or false.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StringCsharp
{
    class IsNullOrEmpty
    {
        static void Main(string[] args)
        {
            string empName = "Satish Panda";
            string address = "";
            if(string.IsNullOrEmpty(address))
            {
                Console.WriteLine("The address is empty");
            }
            else
            {
                Console.WriteLine("The address is not empty");
            }
        }
    }
}

Output:

c# string is null or empty
c# string is null or empty

Extern Alias in C#.Net

Let us disucss on Extern Alias in C#.Net.

The extern alias directive in c#.net gives you the way for accessing a class which has the same name from different physical files. That is you can reference two versions of assemblies that have the same fully-qualified type names. In large projects, you may need to use two or more versions of an assembly in the same application. By using an external assembly alias, the namespaces from each assembly can be wrapped inside root-level namespaces named by the alias, allowing them to be used in the same file.

For example, you may have two class libraries that contain a class with the same name. With the extern keyword, you can use both of those classes at once.

extern alias A;
extern alias B;
using System;
class Program
{
    static void Main()
    {
A.class1.str1 = “First string”;
B.class1.str1 = “Second string”;
Console.WriteLine(A.class1.str1);
Console.WriteLine(B.class1.str1);
    }
}
//   ClassLibrary1
public class class1
{
    public static string str1;
}
// ClassLibrary2
public class class1
{
    public static string str1;
}

Output:
First string
Second string

The extern alias A and B must be mapped to the ClassLibrary1 and ClassLibrary2 DLL files.

To reference two assemblies with the same fully-qualified type names, an alias must be specified on the command line, as follows:
/r:A=ClassLibrary1.dll
/r:B= ClassLibrary2.dll

Few important points you should remember in C#.Net.

  • Some classes contains your C# executable program.
  • The entry point to the program is the static method Main() with void return type.
  • It is a case sensitive language.
  • Whitespaces like enter, tab, space are ignored by the compiler.
  • No need to save your program with the same file name as of your class containing Main() method.
  • There can be multiple Main() methods in your program.
  • The boundaries of namespace, class, and method are defined by opening and closing curly brackets {}.
  • A namespace is only a logical collection of classes.
  • The using keyword is used to inform compiler where to search for the definition of classes that you are about to in your C# program.
  • There are three types of compiler exists in C#, line, block, and documentation.
  • Enclosing your class in some namespace is optional. You can write your program where your class is not enclosed by any namespace.
  • It is not mandatory that the Main method of the program takes ‘string[] args’ as a parameter.

Assembly in c#.net

Now let us check assembly in c#.net.

  • Assemblies are the physical files that contain compiled code. The extension is .exe if they are stand-alone application and .dll if they are reusable components.
  • All .NET classes are contained in assemblies. This is a solution to DLL Hell problem. DLL Hell problem occurs because multiple versions of the COM component are not allowed to install.
  • .Net framework installed all the assemblies to C:\Windows\Assembly directory.
  • An assembly can contain multiple namespaces. Namespaces are a logical way to group classes. Assemblies are a physical package for distributing code.
  • Some Microsoft assemblies are mscorlib.dll, System.Web.dll
  • An assembly can be shared between applications by placing it in the Global Assembly Cache.
  • Assemblies must be strong-named before they can be placed in the Global Assembly Cache.

There are 3 types of assembly in C#.Net

Private assembly:
A private assembly normally used by a single application and is stored in applications directory.

Shared assembly:
A shared assembly is normally stored in global assembly cache and can be used by multiple applications.

Satellite assembly:
Satellites’ assemblies are employed in a multi languages context such an application dedicated to a wide number of people issued from different cultures.

You can use the Gacutil command line utility to install or uninstall assembly to GAC.

To install in an assembly to GAC
Gacutil -i assemblyName

To uninstall an assembly from GAC
Gacutil -u assemblyName

Namespace in C#.Net

Now, let’s see what are namespace in C#.Net?

  • Namespace helps us in arranging code which is like a container. Namespaces can organize all the different types in the class library. Without namespaces, these types would all be grouped into a single long and messy list.
  • The namespace can contain hundred of classes. The namespace can contain classes, structures, interfaces, enumerations, delegates etc.

Microsoft provides various namespaces like
System.Web.UI
System.Web.Services
System.Data
System.IO etc.

We can create a namespace by using namespace keyword like below:

namespace MyWebSites
{
public class EnjoySharePoint
{

}
}

We can use this namespace by using a using statement like below:

using MyWebSites;

After writing the above statement we will be to access the AspDotNetHelp class. Also, you can directly access the class by writing like below:

MyWebSites.EnjoySharePoint

The extension of the namespaces will be .dll

Conclusion

In the above blog, we have discussed the basic concept of C#.net for a beginner who is new to C# with simple examples. Enjoy learning c#.net tutorial step by step.

Check out Best Alternative to InfoPath -> Try Now

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

About Bhawana Rathore

Hello Everyone!! I am Bhawana a SharePoint MVP and having about 8+ years of SharePoint experience as well as in .Net technologies . I have worked in all the versions of SharePoint from wss to Office 365. I have good exposure in Customization and Migration using Nintex, Metalogix tools . Now exploring more in SharePoint 2016 :) Hope here I can contribute and share my knowledge to the fullest. As I believe "There is no wealth like knowledge, and no poverty like ignorance"

View all posts by Bhawana Rathore →