Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is C#?
3.
Need of C#
4.
Features of C#
4.1.
Boolean Conditions
4.2.
Garbage Collection
4.3.
Standard Library
4.4.
Mounting Versions
4.5.
Management of Delegates and Events
4.6.
Indexers
4.7.
Conditional Compilation
4.8.
Simple Multi-Thread 
4.9.
LINQ and Lambda Expressions
5.
C# versions History
6.
Applications of C#
7.
Limitations of C#
8.
C# Fundamentals
9.
C# Implementation
9.1.
C#
10.
Loops in C#
10.1.
if, else, else if condition
10.2.
Switch Statement
10.3.
For loop
10.4.
While loop
10.5.
Do while loop
11.
C# Data Structures
11.1.
Array
11.2.
Tuple
11.3.
Using Constructor of Tuple Class: 
11.4.
Stack
11.5.
Hashtable
12.
Difference between C# and C++
13.
Top 5 C# frameworks 
13.1.
MSTest
13.2.
NUnit
13.3.
xUnit.Net
13.4.
ADO.NET
13.5.
ASP.NET
14.
Advantages of C#
15.
Disadvantages of C#
16.
Frequently Asked Questions
16.1.
What is C#?
16.2.
What is C# used for?
16.3.
Is C# different from C++?
17.
Conclusion
Last Updated: Mar 27, 2024
Easy

Introduction to CSharp

Author Nitika
0 upvote

Introduction

C#(C Sharp) is an object and component-oriented programming language. It provides language constructs to directly support these concepts, making C# a natural language in which to create and use software components.

In this article, we will explore the introduction to C#. We will come across the needs, features, past versions, limitations, advantages, and disadvantages of the C# framework. In addition to that, we will see loops and statements in C# and implement them to grasp more about C# frameworks.

Introduction

What is C#?

C# is an object-oriented programming language created by Microsoft that runs on the .NET Framework combining the computational power of C++ and the ease of Visual Basic. The .NET framework is the runtime platform for C#. This framework contains base-class libraries that consist of reusable code. These libraries let the developers use existing solutions instead of wasting time reinventing them. Also, C# is a platform independent which means you can run C# on any platform, including Windows, Linux, and MacOS. C# was designed to be easy to learn but also be powerful enough to operate several programming tasks.

The C# was originally built with business in mind and was to serve a single company. The C#, the programming language has roots in the C family and has features similar to other popular languages like C++ and Java. 

And as of November 2022, C# ranked #4 on the PYPL Popularity of Programming Language Index, right behind Java and JavaScript. 

Need of C#

  • C# is a programming language that provides numerous advantages to beginners, professional programmers, and developers. 
     
  • C# is a scalable and maintainable programming language.
     
  • C# has a very large community.
     
  • As C# is close to C, C++ and Java, it makes it very easy for the programmers to switch to C# or vice versa.

Features of C#

Features of C#

Boolean Conditions

A Boolean structure represents a Boolean value, which can be true or false. Use Boolean logical operators to conduct logical operations on bool values. The result type of comparison and equality operators is bool. In the if, do, while, and for statements, as well as in the conditional operator?, a bool expression can be used as a controlling conditional expression. 

Garbage Collection

Garbage collection occurs when at least one of several conditions is met. The following are the conditions: Garbage collection is required if the system has insufficient physical memory. Garbage collection occurs when the memory allocated to various objects in heap memory reaches a predefined threshold. When the GC. The collection method is called garbage collection takes place. However, this procedure is only used in uncommon circumstances because the garbage collector generally runs automatically. 

Standard Library

The standard library is intended to contain the bare minimum of types and members required by a C# implementation. As a result, it only contains members that are expressly required by the C# language standard. Namespaces are being added. A complying C# implementation is planned to provide a substantially larger library that allows usable programs to be created.

Mounting Versions

The current C# compiler decides the default language version based on the target framework or frameworks of your project. Although Visual Studio does not give a UI for changing the value, you can do so by altering the csproj file. The default option ensures that you use the most recent language version that is compatible with your target framework. You gain access to the most recent language features that are compatible with the target audience of your project. This default option also ensures that you do not employ a language that requires types or runtime behavior that your target framework does not support. 

Management of Delegates and Events

Delegations and events are effective tools for managing event-driven programming in C#. To enable dynamic invocation, delegated objects serve as references to methods. Events give classes a way to declare and control event handlers, allowing for decoupled and extensible event handling code. As a result, the Observer design pattern can be implemented successfully, supporting applications like event-driven user interfaces and asynchronous programming.

Indexers

Indexers allow instances of a class or struct to be indexed in the same way as arrays may. Without explicitly providing a type or instance member, the indexed value can be set or retrieved. Indexers are similar to properties in that their accessors accept parameters. An indexer's get or set accessor is often composed of a single statement that either returns or sets a value. To handle this case, expression-bodied members give a reduced syntax. As an expression-bodied member, a read-only indexer can be constructed.

Conditional Compilation

Conditional compilation might be beneficial when compiling code for a debug build or when compiling for a specific configuration.  A conditional directive that begins with a #if directive must clearly finish with a #endif directive. #define allows you to define a symbol. By sending the symbol as the expression to the #if directive, the expression evaluates to true.

Simple Multi-Thread 

Threads are lightweight processes that serve as a conduit for the execution of other processes. By default, each process/application operates in a single thread. The application's whole code is performed sequentially in a single thread.  Multithreaded applications introduced the ability to process independent code on multiple threads at the same time. Multithreading helps to reduce execution time while also making optimal use of CPU capacity.

LINQ and Lambda Expressions

Language Integrated Query (LINQ) is a powerful C# feature that allows you to run complicated queries on data collections using a succinct, declarative vocabulary. LINQ has a variety of query operators for filtering, converting, sorting, and aggregating data, among other things. These operators can be combined in a variety of ways to produce clean, useful code.

In C#, lambda expressions are a shorthand for defining anonymous functions. They're very handy in functional programming since they let you create functions inline, which makes your code more expressive and functional.  A lambda expression is made up of a set of input parameters, the lambda operator (=>), and a single expression or block of statements.

C# versions History

C# was first released in 2000 by Microsoft as part of the .NET framework. It was founded by Anders Hejlsberg, better known as the founder of the C# language. Since then, C# has been sanctioned as an international standard for computer programming and is used with Common Language Infrastructure, which is the technical standard for computer platform communications. After its release in 2002, it has immensely evolved and added more and more features with every new release. Here is a list of all the versions of C# since its release.

Version

Description

1.0

v1.0 came with .NET framework 1.0,1.1 having CLR version 1.0 and Microsoft Visual Studio 2002.

2.0

v2.0 came with .NET framework 2.0 having CLR version 2.0, and Microsoft Visual Studio 2005.

3.0

v3.0 came with .NET framework 3.0,3.5 having CLR version 2.0, and Microsoft Visual Studio 2008.

4.0

v4.0 came with .NET framework 4.0 having CLR version 4.0, and Microsoft Visual Studio 2010.

5.0

v5.0 came with .NET framework 4.5 having CLR version 4.0, and Microsoft Visual Studio 2012, 2013.

6.0

v6.0 came with .NET framework 4.6 having CLR version 4.0 and Microsoft Visual Studio 2013, 2015.

7.0

v7.0 came with .NET framework 4.6, 4.6.1, 4.6.2 having CLR version 4.0, and Microsoft Visual Studio 2015 and 2017.

8.0

v8.0 came with .NET framework 4.8 having CLR version 4.0, and Microsoft Visual Studio 2019.

9.0

v9.0 came with .Net 6.0 and Microsoft Visual Studio 2019.

10.0

v10.0 came with .Net 6.0 and Microsoft Visual Studio 2022.

11.0

v11.0 came with .Net 6.0 and Microsoft Visual Studio 2022.

12.0

v12.0 came with .Net 8.0 and Microsoft Visual Studio 2022.

Applications of C#

Applications of C#
  • C# is used in developing web applications and client-server applications using Windows Forms, WPF and UWP.
     
  • It is used in developing games using Unity.
     
  • It is used in web services applications with ASP.NET and ASP.NET Core.
     
  • It is used in console applications.
     
  • It is used in making windows applications that run on desktops.
     
  • It is also used in making Cloud, Azure and Blockchain apps.

Limitations of C#

  • The C# framework is not as flexible as that of C++.
     
  • The C# errors can be complex in nature, therefore requiring considerable knowledge and experience.
     
  • It has a poop GUI (Graphical User Interface).

C# Fundamentals

In C#, a data type is used to communicate with the compiler on the kinds of data that a variable can hold inside it. C# has many built-in data types like Boolean, Integer, Float, Decimal, and much more.

The system allocates some memory space to store values whenever a variable is declared

Example

class Test
{
 static void Main(string[] args)
    {
string stringVariable = "abc";
         
    }
}


C# has a specified range of values for each of the data types.

Let us look at some of the values and their ranges.

Type

Representation

Range

Default Value

string

A series of characters

   

char

A Unicode character

   

object

Object type

   

bool

Boolean value

True or False

False

byte

8-bit unsigned integer

0 to 255

0

decimal

decimal values with 28-29 significant digits

(+ or -)1.0 x 10e-28 to 7.9 x 10e28

0.0M

double

64 bit double-precision floating point type

(+/-)5.0 x 10 raise to -324  to (+/-)1.7 x 10 raise to 308

0.0D

int

32 bit signed integer type

-2,147,483,648 to 2,147,483,647

0

float

32 bit single-precision floating point type

-3.4 x 10 raise to 38  to + 3.4 x 10 raise to 38

0.0F

long

64 bit signed integer type

-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

0L

uint

32 bit unsigned integer type

0 to 4,294,967,295

0

short

16 bit signed integer type

-32,768 to 32,767

0

ulong

64 bit unsigned integer type

0 to 18,446,744,073,709,551,615

0

In c# we also have something called variables which is the name that we provide to store our values. Each one has its own type and is further defined by its characteristics like type and size of value it can store. here are some types of variables present in the C# language.

A variable in C# is always defined by using a data type. 

<data type> <variable name>;

Further, the data types can be divided into two categories based on how the value is stored in their memory. Thus, we have:

  • Value Types
    In this data type the variable holds a data value within its personal memory space. Hence, we can say that these data types directly hold their values.
    For example,  
    int A = 40;
    We can see that the integer ‘A’ directly holds the value of 40.
     
  • Reference Types
    In this data type, it doesn’t directly hold values but instead, it holds the address where the value might be stored. In other words, the reference type variable holds the reference to a particular memory location that may hold the data.
    There are three reference types:
    • Object type: can be assigned with the values of any of the other types. For example,
      object A = 40;
       
    • Dynamic type: stores any dynamic variable or data type. For example,
      dynamic A= 12345;
       
    • String: assigns a series of character values to a variable. For example,
      String A= “Coding Ninjas”;

C# Implementation

In the following program, we will be performing all arithmetic operations on two numbers input by the user.

  • C#

C#

using System;
namespace TechStudyCSharp
{
   class Program
   {
       static void Main(string[] args)
       {
           int num1;
           int num2;
           int sum, sub, mult, mod;
           float div;
           Console.WriteLine("Enter first number :");
           num1 = Convert.ToInt32( Console.ReadLine());
           Console.WriteLine("Enter second number :");
           num2 = Convert.ToInt32(Console.ReadLine());
           sum = num1 + num2;
           sub = num1 - num2;
           mult = num1 * num2;
           mod = num1 % num2;
           div = (float)num1 / num2;
           Console.WriteLine("\nSum of numbers: " + sum);
           Console.WriteLine("Difference of numbers: "+ sub);
           Console.WriteLine("Product of numbers: " + mult);
           Console.WriteLine("Modulus of numbers: " + mod);
           Console.WriteLine("Quotient of numbers: " + div);
           Console.ReadKey();
       }
   }
}


Output

Enter first number :
20
Enter second number :
30
Sum of numbers: 50
Difference of numbers: -10
Product of numbers: 600
Modulus of numbers: 20
Quotient of numbers: 0.6666667

Loops in C#

if, else, else if condition

The if statement is used to specify a code block that is to be executed if the given condition is True.

if (condition) 
{
  // code block  
}


Whereas the else statement is used to specify the code block that is to be executed if the condition is False.
if (condition)


{
  // code block (True) 
} 
else 
{
  // code block (False)
}


And finally, the else if statement is used to specify a new condition if the first condition is False.


if (condition1)
{
  // block of code to be executed if condition1 is True
} 
else if (condition2) 
{
  // block of code to be executed if the condition1 is false and condition2 is True
} 
else
{
  // block of code to be executed if the condition1 is false and condition2 is False
}

Switch Statement

The switch statement in C# gives an efficient way to transfer the execution to different parts of a program based on the values of the expression. The switch statement can either be of integer type such as int, char, byte, and short, or of an enumeration type, or of string type. The break keywords break out of the switch code block and the default keyword specifies some code to run where there is no case.

switch(expression) 
{
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
    break;
}

For loop

A for loop is used to write a loop that needs to execute a specific number of times. After the condition is evaluated, the body of the loop is executed if the condition comes out to be true. If it is false, the body of the loop does not execute and the program flow control jumps to the next statement of the for loop.

for (loop variable initialization; testing condition; 
                              increment/decrement)
{    
    // statements to be executed
}

While loop

A while loop statement repeatedly executes a target statement as long as a given condition is true. When the condition is false, the program control passes to the line that is immediately after the loop.

while (boolean condition)
{
   loop statements
}

Do while loop

The do...while loop checks its condition at the end of the loop. After the condition is evaluated, if it is true, the flow of control jumps back up to do, and the statement in the loop executes again. This process repeats until the given condition becomes false.

do
{
    statements
}
while (condition);

C# Data Structures

In this section, we will learn about the data structures in the C# framework.

Array

In C#, Arrays store multiple values in a single variable instead of declaring separate variables for each value. One can declare an array by specifying the type of its elements. In C#, all predefined and user-defined reference types and value types inherit directly or indirectly from Object.
To declare an array, we define the variable type with square brackets.
string[] Ninjas;
To insert values to it, we can use an array literal and place the values in a comma-separated list inside curly braces.
string[] Ninjas = {"C#", "frameworks"};
and for an array of integers,
int[] integers = {1, 2, 3, 4};

Tuple

In C#, a tuple is a data structure that contains a sequence of elements of different data types. One can create, manipulate, and access data using tuples. It is also used to store duplicate elements.
In C#, there are two ways to create tuples:
 

Using Create Method:
// Method for 1-tuple
Create(T1)



// Method for 2-tuple
Create(T1, T2)



// Method for 8-tuple
Create(T1, T2, T3, T4, T5, T6, T7, T8)

Using Constructor of Tuple Class: 

// Constructor for single elements
Tuple <T1>(T1)


// Constructor for two elements
Tuple <T1, T2>(T1, T2)
.
.
.
 // Constructor for eight elements
Tuple <T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest)

Stack

In C# the stack is a special type of collection that stores elements in LIFO style, which is (Last In First Out). Stack is helpful to store temporary data in LIFO style. The stack includes the generic stack <T> and non-generic Stack collection classes. 

For creating an object of the Stack<T>, you need to specify a type parameter for the type of elements it can store. 

// create Integer type stack
Stack<int> stack1 = new Stack<int>();


// create String type stack
Stack<string> stack2 = new Stack<string>();


Here are some of the    Stack<T> properties and methods-
 

Property

Usage

Count

Returns the total count of elements in the Stack.

Method

Usage

Push(T)

Inserts an item at the top of the stack.

Peek()

Returns the top item from the stack.

Pop()

Removes and returns items from the top of the stack.

Contains()

Checks whether an item exists in the stack or not.

Clear()

Removes all items from the stack.

Hashtable

In C#, a hashtable is a non-generic collection that stores key-value pairs. Or in simpler words, a Hashtable is used to create a collection which uses a hash table for storage. The capacity of a Hashtable is the number of elements it can hold. In Hashtable, key objects must be immutable.
The Hashtable class has 16 different types of constructors that are used to create a hashtable. They are

CONSTRUCTOR

Hashtable()

Hashtable(IDictionary)

Hashtable(IDictionary, IEqualityComparer)

Hashtable(IDictionary, IHashCodeProvider, IComparer)

Hashtable(IDictionary, Single)

Hashtable(IDictionary, Single, IEqualityComparer)

Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)

Hashtable(IEqualityComparer)

Hashtable(IHashCodeProvider, IComparer)

Hashtable(Int32)

Hashtable(Int32, IEqualityComparer)

Hashtable(Int32, IHashCodeProvider, IComparer)

Hashtable(Int32, Single)

Hashtable(Int32, Single, IEqualityComparer)

Hashtable(Int32, Single, IHashCodeProvider, IComparer)

Hashtable(SerializationInfo, StreamingContext)

Difference between C# and C++

Properties

C#

C++

Type

C# is a high-level programming language

Comprises both high-level and low-level language because it is built directly over C.

It is an intermediate language

Compilation Process

It compiles programs to CLR that is interpreted by Just In Time(JIT) in ASP.NET

It compiles programs to machine code

Memory Management 

Management is done automatically 

Memory management is done manually 

Difficulty

C# is simple and is easy to understand

It is hard to understand and has complex features

Platform

Rarely used outside Windows Operating System 

Used in multiple platforms such as Linux, Windows, macOS, etc.

Standalone Applications

Development of standalone applications is impossible

It is capable of developing standalone applications or applications that run locally without requiring any other functions to be running

Object-Oriented

It is purely an object-oriented language

It is not a completely object-oriented language. 

Bound Check

Supports the bound check of arrays

Does not allow the bound check of arrays

Garbage Collection

Supports cleaning of unreferenced parts in a program

 

Does not support cleaning of unreferenced parts in a program

Pointers

Can only be used in unsafe mode

Pointers can be used anytime

Binaries

It is high and has a lot of overhead libraries

The size of binaries is low and lightweight

Switch Statement

The switch statement may or may not be a string

The switch statement in a program cannot be a string

Access Specifiers

Access modifiers are public, private, protected, internal & protected internal are used for access specifiers.

The access modifiers are public, private, protected and do not contain internal & protected internal access modifiers.

Project type 

It is used in modern application development 

It is used for projects that focus on the access of the hardware and better performance

Top 5 C# frameworks 

MSTest

MSTest is used for unit testing. It provides the required tools to verify & validate the source code. This C# framework identifies tests through different attributes under which the test code is present. MSTest is open-source, and the project is hosted on GitHub. Testers can create tests, and after running them, they can view the results in the IDE.

NUnit

NUnit is a unit testing framework for all .NET languages. Developers can write and execute automated tests for their code. NUnit includes asserting methods to ensure that the code under test is working correctly. It is favoured among developers for making sure that their code is high in quality and flawless.

xUnit.Net

xUnit.Net was developed by Brad Wilson and Jim Newkirk, inventors of NUnit C# Framework. xUnit.net is the latest technology for unit testing C# which has become popular due to its clarity, expressiveness, and extensibility. xUnit.Net was built in such a way that it doesn't require any installation such as XCopy.

ADO.NET

ADO.NET is a part of the .Net C# Framework, which is used to designate connections between applications and data sources. It consists of classes that are used to connect, recover, insert and delete data. The ADO.NET framework has two main components for accessing and manipulating data: the .NET Framework data provider and the DataSet.

ASP.NET

ASP.NET is a technology which works on the .Net framework. The web development platform provides a programming model and a complete software infrastructure. It works on top of the HTTP protocol and makes use of the HTTP commands. The ASP.NET is used to create interactive, data-driven web applications over the internet.

Advantages of C#

Here are some of the advantages of C#:

  • One of the most prominent advantages of C# is that it is type-safe. It means that the types can interact only through protocols that they define, which ensures the internal consistency of each type
     
  • Memory loss is not much of a problem as compared to C++. This happens because C# has an auto garbage collection, meaning that one does not have to manually free the memory like in C++ when using pointers
     
  • C# is easy to develop, and the rich class library makes many functions easy to implement
     
  • C# supports the distributed system

Disadvantages of C#

Here are some of the disadvantages of C#:

  • C# is slower in terms of compilation time in addition to the speed of the application itself. This is because C# first compiles into an intermediary language and then into machine language before being executed
     
  • C# is a more complex programming language to learn as compared to Python, Perl, PHP, or Ruby
     
  • C# does not perform low-level programming tasks like interacting directly with hardware, creating drivers, or working with firmware

Frequently Asked Questions

What is C#?

C# is an object-oriented programming language that enables developers to create many strong and snug applications running in .NET. The C# programming language is intended to be a straightforward, modern, general-purpose programming language. It can be integrated with Microsoft and is also widely used in game development.

What is C# used for?

C# is used to build various types of programs, mobile, web and Windows applications using .NET or open-source software. In addition to that, C# is also used for cloud-based services, enterprise software and games. Microsoft, Stack Overflow, Trustpilot, City Bank and many more are some of the large companies which make use of C#.

Is C# different from C++?

Yes, C# is different from C++. C# is a high-level programming language, while C++ comprises both high-level and low-level language because it is built directly over C. Also, C# is simple and easy to understand but C++ is hard to understand and has complex features

Conclusion

In this article, we explored the depths of C#. Hope this article helps you in your learning journey.

For more information, you can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more!

C++ vs Java

You can also look at the Python Library for more Python-related content.

Head over to our practice platform Coding Ninjas Studio to practise top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!!

Happy Learning Ninja!!

Live masterclass