2 • C#.NET Basics
2 • C#.NET Basics
1. What is C#.NET?
2. Advantages of using the .NET Framework from the C# point of
view.
3. Different Types of applications developed using C#.NET.
4. What is the visual studio?
5. What is a console application?
6. How to Create a console application using the visual studio?
7. Example of console application using C#.
8. Understanding the basic structure of a C# Program.
Importing section
Namespace Declaration
Class Declaration
Main() method
So, here, first, we will understand what is C#.Net and Visual Studio and what
type of applications we can develop using C#.Net. Then we will discuss the
basic structure of a C# program using a console application.
What is C#.NET?
1. C#.NET is one of the Microsoft programming languages.
2. It is the most powerful programming language among all programming
languages available in the .NET framework because it contains all the
features of C++, VB.NET, JAVA, and also some additional features.
3. C#.NET is a completely object-oriented programming language.
4. This programming language is intended to be a simple, modern,
general-purpose object-oriented programming language.
Advantages of using the .NET framework from the C# point of view.
1. It provides GUI features. Earlier programming languages like C, C++
do not support GUI features but C#.NET will provide complete GUI
features. All GUI features are getting from the framework.
2. Any database will support and perform the operations. Using ADO.NET
technology we can perform the operations with any DB server.
ADO.NET is also a part of the framework.
3. It prepares WEB applications. Using ASP.NET technology we can
implement web applications. ASP.NET is needed language support so
we are using either VB or C# as language supporters. ASP.NET is also a
part of the framework.
Different Types of applications developed using C#.NET.
1. Windows applications
2. Web applications
3. Console applications
4. Class library:
What is the visual studio?
Visual Studio is one of the Microsoft IDE tools. Using this tool we can
implement applications with the .NET framework. This tool provides some
features such as
1. Editor
2. Compiler
3. Interpreter
What is a console application?
1. These applications contain a similar user interface to the OS like MS-
DOS, UNIX, etc.
2. The console application is known as the CUI application because in this
application we completely work with the CUI environment.
3. These applications are similar to c or c++ applications.
4. Console applications do not provide any GUI facilities like the mouse
pointer, colors, buttons, menu bars, etc.
Let’s First Understand the Basic Structure of C# Program using a console
application.
<span style="font-family: arial, helvetica, sans-serif;">//List of
classlibraries /namespaces
namespace namespacename
class classname
//statements
</span>
In the next window, select Installed => Templates => Visual C# from
the left pane. From the middle Panel, select Console Application. Then
specify the application name and location and finally click on the OK button
as shown in the below image.
Once you click on the OK button, it will take some time to create the project
solution for us.
Let’s create one program to print a welcome message on the
console.
Whenever you create a console application, by default the .NET Framework
creates a class (i.e. Program class) for us. Let’s modify the Program.cs file as
shown below to print a welcome message on the console screen.
<span style="font-family: arial, helvetica, sans-serif;">using System;
namespace FirstProgram
class Program
Console.WriteLine("Welcome to C#.NET");
Console.ReadKey();
}
</span>
Resetcolor() Reset the background and foreground color to its default state
Write(“string”
) Display the specified message on the console window
WriteLine(“str Same as the write method but automatically moves the cursor to the
ing”) next line after printing the message.
Write(variable
) Displays the value of the given variable
WriteLine(vari Displays the value of the given variable along with moving the cursor
able) to the next line after printing the value of the variable.
Read a single character from the keyboard and returns its ASCII value.
Read() The Datatype should be int as it returns the ASCII value.
Reads a string value from the keyboard and returns the entered value
only. As it returns the entered string value so the DataType is going to
ReadLine() be a string.
This method reads a single character from the keyboard and returns
that character. The Datatype should be int as it returns the ASCII
ReadKey() value. It is a STRUCT Data type which is ConsoleKeyInfo.
Example: Program to show the use of the Write and WriteLine
method:
<span style="font-family: arial, helvetica, sans-serif;">namespace
FirstProgram
class Program
Console.WriteLine("HELLO");
Console.Write("WELCOME");
Console.ReadKey();
}
</span>
Output:
class Program
Console.WriteLine(name);
Console.ReadKey();
</span>
Output:
class Program
Console.ReadKey();
</span>
Output:
Example: Program to take two numbers as input from the console and then
print the summation in the console.
<span style="font-family: arial, helvetica, sans-serif;">namespace
FirstProgram
{
class Program
int a, b, c;
a = int.Parse(Console.ReadLine());
b = Convert.ToInt32(Console.ReadLine());
c = a + b;
Console.ReadKey();
</span>
Output:
Note: The ReadLine method always accepts the value in the form of a string.
So we need to convert the values to the appropriate type. In the above
example, we are converting the values to integer type by
using int.Parse and Convert.ToInt methods. We will discuss these
concepts in detail in a later article.
Example:
Program to accept employee details like empno, name, salary, address, job,
and print the accepted information.
<span style="font-family: arial, helvetica, sans-serif;">namespace
FirstProgram
class Program
EID = int.Parse(Console.ReadLine());
ENAME = Console.ReadLine();
SALARY = int.Parse(Console.ReadLine());
ADDRESS = Console.ReadLine();
JOB = Console.ReadLine();
Console.ReadKey();
</span>
Output:
Example:
Program to accept student no, student name, mark1, mark2, mark3 and
calculate the total mark and average marks and printing accepted
information.
<span style="font-family: arial, helvetica, sans-serif;">namespace
FirstProgram
class Program
string SNAME;
SNO = int.Parse(Console.ReadLine());
SNAME = Console.ReadLine();
MARK1 = int.Parse(Console.ReadLine());
MARK2 = int.Parse(Console.ReadLine());
MARK3 = int.Parse(Console.ReadLine());
AVERAGE = TOTAL / 3;
Console.WriteLine("\n\n\nTHE STUDENT DETAILS ARE GIVEN BELOW :");
Console.ReadKey();
</span>
Output:
Example:
Program to show the use of BackgroundColor, ForegroundColor, and Title
properties of Console class in C#.
<span style="font-family: arial, helvetica, sans-serif;">namespace
FirstProgram
class Program
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("BackgroundColor Blue");
Console.WriteLine("ForegroundColor White");
Console.ReadKey();
</span>
Output:
Data Types in C#
Data Types in C# with Examples
In this article, I am going to discuss the Data Types in C# with examples.
Please read our previous article where we discuss the Console class
Methods and Properties in C# before proceeding to this article. As a
developer, it is very important to understand the Data Type in C#. This is
because you need to decide which data type to use for a specific type of
value. As part of this article, we are going to discuss the following pointers
related to C# data type in detail.
1. Why we need data types in C#?
2. What is a data type in C#?
3. Different types of Data type in C#.
4. What is Value Data Type in C#?
5. What is Reference Data Type in C#?
6. Examples using Built-in Data Types in C#.
7. What is Pointer Type?
8. Examples using Escape Sequences in C#.
Why we need data types in C#?
The Datatypes in C# are basically used to store the data temporarily in the
computer through a program. In the real world, we have different types of
data like integer, floating-point, character, string, etc. To store all these
different kinds of data in a program to perform business-related operations,
we need the data types.
What is a data type in C#?
The Datatypes are something which gives information about
1. Size of the memory location.
2. The range of data that can be stored inside that memory location
3. Possible legal operations that can be performed on that memory
location.
4. What types of results come out from an expression when these types
are used inside that expression.
The keyword which gives all the above information is called the data type.
What are the different types of Data types available in C#?
A data type in C# specifies the type of data that a variable can store such
as integer, floating, character, string, etc. The following diagram shows
the different types of data types available in C#.
There are 3 types of data types available in the C# language.
1. Value Data Type
2. Reference Data Type
3. Pointer Data Type
Let us discuss each of these data types in detail
What is Value Data Type in C#?
The data type which stores the value directly called the Value Data Type.
They are derived from the class System.ValueType. The examples are int,
char, and float which stores numbers, alphabets, and floating-
point numbers respectively. The value data types in C# again classified into
two types are as follows.
1. Predefined Data Types – Example includes Integer, Boolean,
Float, etc.
2. User-defined Data Types – Example includes Structure,
Enumerations, etc.
Based on the Operating system (32 or 64-bit), the size of the memory of the
data types may change. If you want to know the actual size of a type or a
variable on a particular operating system, then you can make use of
the sizeof method.
Let’s understand this with an example. The following example gets the size
of int type on any platform.
namespace FirstProgram
{
class Program
Console.ReadKey();
class Program
Console.WriteLine(Name);
Name = "One\nTwo\nThree";
Console.WriteLine(Name);
Name = "c:\\Pranaya\\Dotnettutorials\\Csharp";
Console.WriteLine(Name);
// C# verbatim literal
Name = @"c:\Pranaya\Dotnettutorials\Csharp";
Console.WriteLine(Name);
Console.ReadKey();
}
}
Output:
C# String in Depth
C# String in Depth with Examples
In this article, I am going to discuss C# String in Depth with examples.
Please read our previous article, where we discussed C# Data Types in
detail. As a developer, it is very important to understand the concept of C#
strings and I am also sure you are using the C# string in all of your projects.
But there are many things that you should know from a performance point of
view. So, as part of this article, we are going to discuss the following pointers
in detail with examples.
1. Strings are reference types
2. Understanding the difference between string(small) vs
String(Capital).
3. Why strings are immutable?
4. How we can improve performance using String intern?
5. StringBuilder for concatenation.
6. Why they made string is immutable.
Strings are reference types in C#:
C# strings are objects i.e. they are not normal data types. For example, if we
define some variables using int or double data types as shown below,
Then if you right-click on the data type and go to the definition then you will
see that they are struct as shown in the below image. Struct means they are
value type.
On the other hand, if you define a variable with string data type as shown
below.
Then if you right-click on the string data type and click on go to definition
then you will see that it is a class. Class means reference data type.
So, the first point that you need to remember is strings are reference types
while other primitive data types are struct types i.e. value type in C#.
What are the Differences between String(Capital) vs string(small) in
C#?
In C#, you can use the string in two ways i.e. you can use the string using
capital S (i.e. String) or by using the small “s” (i.e. string) as shown in the
below image.
Now the question that should come to your mind is what is the difference
between these two (string vs String) in C#. Let’s understand this. The small
string is actually an alias of String (Capital string). If you right-click on the
small string and if you go to the definition then you will see that the actual
class name is capital string i.e. String as shown in the below image.
You can use any one of them i.e. either string or String. But as per the
naming convention when you are creating a variable use the small string (i.e.
string) and whenever you want to invoke methods on the string then use the
capital string (i.e. String) as shown in the below image.
So, when the above two statements are executed, internally two memory
locations are created. One with the value DotNet and the current one with
the value Tutorials and the current one is going to be referred in the
program. So, each time, we assign a new value to the string variable, a new
object is created and this is the reason why strings are immutable in C#.
But this is not the case with a value type. For example, please have a look at
the below two statements. When the first statement is executed one
memory location is created and assign the value 100 and when the second
statement is executed, it will not create a new memory location rather it will
override the value of the same memory location.
using System.Diagnostics;
namespace StringDemo
class Program
Console.WriteLine("Loop Started");
var stopwatch = new Stopwatch();
stopwatch.Start();
str = Guid.NewGuid().ToString();
stopwatch.Stop();
Console.WriteLine("Loop Ended");
Console.ReadKey();
Output: When you execute the program, you will get the following output.
The time may vary in your machine.
namespace StringDemo
class Program
Console.WriteLine("Loop Started");
stopwatch.Start();
ctr = ctr + 1;
stopwatch.Stop();
Console.WriteLine("Loop Ended");
Console.ReadKey();
}
}
Output:
As you can see in the above output, it only took 84 milliseconds to execute
the loop.
Example: String with Same value in C#
Let us understand what will happen if we assign the same value to the string
variable again and again with an example in C#. As you can see in the below
example, which is exactly the same as the first example, but here instead of
using GUID, we are assigning a fixed value to the string str variable.
using System;
using System.Diagnostics;
namespace StringDemo
class Program
Console.WriteLine("Loop Started");
stopwatch.Start();
stopwatch.Stop();
Console.WriteLine("Loop Ended");
Console.ReadKey();
Output:
As you can see in the above output it only took 95 milliseconds. This is
because in this case fresh objects are not created each time the loop
executes. Now, the question that should come to your mind is why? The
answer is String intern. So, let us understand string interning in detail.
String Intern in C#:
The String Intern in C# is a process that uses the same memory location if
the value is the same. In our example, when the loop executes for the first
time, it will create a fresh object and assign the value “DotNet Tutorials” to
it. When the loop executes 2nd time, before creating a fresh object, it will
check whether this “DotNet Tutorials” value is already there in the
memory, if yes then it simply uses that memory location else it will create a
new memory location. This is nothing but C# string interning.
So, if you are running a for loop and assigning the same value again and
again, then it uses string interning to improve the performance. In this case,
rather than creating a new object, it uses the same memory location. But
when the value changes it will create a new fresh object and assign the value
to the new object.
StringBuilder for Concatenation in C#:
As we already discussed if the value changes then every time it will create a
new fresh object in C# and this is because of the Immutability behavior of
the string. The C# string immutability behavior can be very very dangerous
when it comes to string concatenation. Let us understand string
concatenation in C# with an example and understand the problem. In the
below example, we are concatenating the string using the for loop.
using System;
using System.Diagnostics;
namespace StringDemo
class Program
Console.WriteLine("Loop Started");
stopwatch.Start();
stopwatch.Stop();
Console.WriteLine("Loop Ended");
Console.ReadKey();
}
Output:
As you can see in the above image, it took approximately 5473 milliseconds
to execute the loop. In order to understand how it executes the loop, please
have a look at the below image. The loop executes the first time, it will
create a new memory location and store the value “DotNet Tutorials”. For
the second time, it creates another fresh memory location (fresh object) and
stores the value “DotNet Tutorials DotNet Tutorials” and the first memory
location will be going for garbage collection. And the same process will
continue i.e. each time the loop executes a new memory location will be
created and previous ones will be going for garbage collection.
using System.Diagnostics;
using System.Text;
namespace StringDemo
{
class Program
Console.WriteLine("Loop Started");
stopwatch.Start();
stringBuilder.Append("DotNet Tutorials");
stopwatch.Stop();
Console.WriteLine("Loop Ended");
Console.ReadKey();
}
Output:
As you can see in the above output, it only took 1 millisecond to concatenate
the string comparing to 5473 using string. This is because every time the for
loop runs it will not create fresh objects rather than it will use the same
memory location i.e. the same old object which drastically improves the
application performance.
Why they made C# String Immutable?
Now the question is why they made strings as Immutable in C#. They made
Strings as Immutable for Thread Safety. Think of one situation where
you have many threads and all the threads want to manipulate the same
string object as shown in the below image. If strings are mutable then we
have thread-safety issues.
In case if you are new to thread safety, I strongly recommended you to read
the following article, where we discussed Thread and Thread Safety in detail.
https://dotnettutorials.net/lesson/multithreading-in-csharp/
Static Keyword in C#
Static Keyword in C# with Examples
In this article, I am going to discuss why do we need the keyword Static
in C# with examples. Please read our previous article, where we
discussed C# String in detail. At the end of this article, I am sure you will
understand the need and use of Static Keyword in C# with examples.
Why do we need Static Keyword in C#?
If you ask this question to any developers, they most probably answer you
that the static keyword is used in Factory Design Pattern, Singleton Design
Pattern as well as used for data sharing, etc. But I think, the static keyword is
used for three basic purposes. And in this article, we will discuss these three
purposes in detail. I hope you are going to enjoy this article.
Example to understand the Static Keyword in C#:
Let us understand the need and use of the C# Static Keyword with an
example. First, create a console application with the name
StaticKeyowrdDemo.
CountryMaster.cs:
Once you created the Console application, then create a class file with the
name CountryMaster.cs and then copy and paste the following code into
it.
namespace StaticKeyowrdDemo
get
return System.Environment.MachineName;
if(value.Length > 0)
return true;
return false;
{
//Insert the data
Again while inserting the CountryMaster record into the database, we also
need to check both CountryCode and CountryName should not be empty. To
check if empty or not, we also like to use the IsEmpty method which is
defined in the Customer class rather than writing the complete logic here.
Further, if you notice, the IsEmpty method of the Customer class is private,
so in order to use that method in CountryMaster class, we need to change it
to the public as shown in the below image.
The CountryMaster class has logic to retrieve the Computer name and we
want to use that logic in the Customer class so we made the ComputerName
property public. Similarly, the Customer class has logic check whether a
value is empty or not and we also want that logic in the CountryMaster class,
so we made the IsEmpty method as public. As long as we did this, we violate
the encapsulation principle.
How we are violating the Encapsulation Principle?
Let us understand how we are violating the encapsulation principle. Modify
the Program class as shown below. Once you created the Customer class
object, then you can see the public member of that class as shown in the
below image.
As you can see, we have exposed the CustomerCode, CustomerName, Insert,
and IsEmpty methods. There is a clear violation of abstraction. Abstraction
means shows only what is necessary. So, the external person who is
consuming your class, should see and consume
the CustomerCode, CustomerName, and Insert method. But should not
see the IsEmpty method. The IsEmpty method is for internal use i.e. use by
other methods not by the consumer of the class. As we make the IsEmpty
method as public, we are violating the Encapsulation principle.
In the same way, we also violating the abstraction principle with
the CountryMaster object as we are exposing
the ComputerName property to the external world that is going to consume
the class as shown in the below image. The ComputerName property is for
internal use only.
Note: With the above, we are achieving code reusability (reusing the
ComputerName and IsEmpty method) but violating the encapsulation
principle.
How to solve this problem?
How to solve the above problem means how should we achieve code
reusability but without violating the OOPs principles (i.e. Encapsulation
Principle). In order to achieve both, let us add a new class and then move
those two functions into that class. Create a class file with the
name CommonTask.cs and then copy and paste the following code in it.
namespace StaticKeyowrdDemo
if (value.Length > 0)
return true;
return false;
return System.Environment.MachineName;
Please remove the IsEmpty() method from the Customer class and the
ComputerName property from the CountryMaster class. Now both the logic
which violates the OOPs principle has been moved to
the CommonTask class.
Modifying Customer class:
Now modify the Customer class as shown below. As you can see, in the
constructor we set the value of the MachineName private variable and in the
Insert method, we create an instance of CommonTask class and Invoke
the IsEmpty method.
namespace StaticKeyowrdDemo
public Customer()
MachineName = commonTask.GetComputerName();
if(!commonTask.IsEmpty(CustomerCode) && !
commonTask.IsEmpty(CustomerName))
{
public class CountryMaster
get
return commonTask.GetComputerName();
if (!commonTask.IsEmpty(CountryCode) && !
commonTask.IsEmpty(CountryName))
}
}
if (value.Length > 0)
{
return true;
return false;
return System.Environment.MachineName;
Once you make the class static, then you cannot use the new keyword with
the static class to create an instance, rather you need to invoke
the IsEmpty and GetComputerName methods by using the class name.
Internally only one instance of the static class gets created by CLR which
serves all the clients.
Modify the Customer class:
Now modify the Customer class as shown below. As you can see, now we are
invoking the GetComputerName and IsEmpty method using the class
name i.e. CommonTask.
namespace StaticKeyowrdDemo
MachineName = CommonTask.GetComputerName();
if(!CommonTask.IsEmpty(CustomerCode) && !
CommonTask.IsEmpty(CustomerName))
get
return CommonTask.GetComputerName();
if (!CommonTask.IsEmpty(CountryCode) && !
CommonTask.IsEmpty(CountryName))
Due to the single instance behavior, the static class is also going to be used
to share the common data.
class Example
public Example(int x)
this.x = x;
//Creating object1
//Creating object2
Console.ReadLine();
Output:
class Example
int x = 100;
//we can access non static members X with the help of Example object
//We can access the static member directly or through class name
Example obj = new Example();
//Console.WriteLine(obj.x + Example.y);
void Mul()
//we can access the non-static members directly or through this keyword
// Statid to Static
Example.Add();
Add();
// Static to non-static
obj.Mul();
Console.ReadLine();
Output:
class Example
static Example()
public Example()
Console.ReadLine();
}
}
Output:
return fahrenheit;
}
return celsius;
class TestTemperatureConverter
Console.Write(":");
double F, C = 0;
switch (selection)
{
case "1":
F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
break;
case "2":
C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
break;
default:
break;
Console.ReadKey();
}
Output:
class ConstExample
class Program
{
static void Main(string[] args)
Console.WriteLine(ConstExample.number);
Console.WriteLine(no);
//no = 20;
Console.ReadLine();
class ReadOnlyExample
class Program
Console.WriteLine(readOnlyInstance.number);
Console.ReadLine();
}
}
In the above example, the read-only variable is assigned with a value at the
time of its declaration and is accessed using the instance of the class rather
than using the class name as read-only variables are non-static in
nature. Suppose, you may have another instance of the class, which might
have the read-only number variable assigned to a different value based on
some conditions. Can I do it? Yes, because the read-only variables are known
at runtime.
Example: Read-only Variable Initialization through Constructor in C#
In the below example, we are initializing the readonly variable through the
class constructors. You can directly initialize the readonly variables at the
time of declaration or you can initialize through class constructors. Once
initialized then you cannot change the value of readonly variables in C#.
namespace ReadOnlyDemo
class ReadOnlyExample
public ReadOnlyExample()
number = 20;
number = 100;
}
}
class Program
Console.WriteLine(readOnlyInstance.number);
// readOnlyInstance.number = 20;
Console.WriteLine(readOnlyAnotherInstance.number);
Console.ReadLine();
Output:
As you can see in the above output, different values coming out of the
program’s output for the two different instances of the class. Hence it proves
that read-only variables are also immutable values that are known at
runtime and do not change their values for the life of the program.
Let us understand Const, Readonly, Static and non-static variables
with one example:
namespace ReadOnlyConstDemo
{
class Example
this.x = x;
this.flag = flag;
Console.WriteLine(Example.y);
Console.WriteLine(Example.PI);
Console.ReadLine();
}
OUTPUT:
Properties in C#
Properties in C# with Examples
In this article, I am going to discuss the Properties in C# with examples.
Please read our previous article before proceeding to this article where we
discussed the Const and Read-Only Variables in C#. As part of this
article, we are going to discuss the following pointers related to properties in
detail.
1. Why do we need properties in C#?
2. What is a Property in C#?
3. What are Accessors in C#?
4. What is Set Accessor?
5. What is Get Accessor?
6. What are the different types of properties supported by
C#.NET?
7. What is Read-only Property?
8. What is Write only property?
9. What is Read Write property?
10. What are the advantages of using Properties in C#?
11. What is the default accessibility modifier of Accessors in
C#?
12. What are symmetric and asymmetric accessors in C#?
13. What are Auto-Implemented Properties in C#?
14. Why do we need Properties in real-time applications with
an example?
Why do we need Properties in C#?
In order to encapsulate and protect the data members (i.e. fields), we use
properties in C#. The Properties in C# are used as a mechanism to set and
get the values of a class outside of that class. If a class contains any value in
it and if we want to access those values outside of that class, then you can
provide access to those values in 2 different ways
1. By storing the value under a public variable we can give access to the
value outside of the class.
2. By storing that value in a private variable we can also give access to
that value outside of the class by defining a property for that variable,
What is a Property in C#?
A property in C# is a member of a class which is used to set and get the data
from a data field of a class. The most important point that you need to
remember is. a property in C# is never used to store data, it just acts as an
interface to transfer the data. We use the Properties as they are the public
data members of a class, but they are actually
special methods called accessors.
What are Accessors in C#?
The Assessors are nothing but special methods which are used to set and get
the values from the underlying data member. Assessors are of two types
such as
1. set accessor
2. get accessor
What is set Accessor?
The set accessor is used to set the data (i.e. value) into a data field. This set
accessor contains a fixed variable named “value”. Whenever we call the
property to set the data, whatever data (value) we are supplying that will
come and store in the variable “value” by default.
Syntax: set { Data Field Name = value; }
What is Get Accessor?
The get accessor is used to get the data from the data field. Using this get
accessor you cannot set the data.
Syntax: get { return Data Field Name; }
What are the different types of properties supported by C#.NET?
The C#.NET supports four types of properties. They are as follows
1. Read-only property
2. Write only property
3. Read Write property
4. Auto-implemented property
Let us understand each of the above properties in details with examples.
What is Read-only Property in C#?
The Read-only property is used to read the data from the data field. Using
this property you cannot set the data into the data field. This property will
contain only one accessor i.e. “get” accessor.
Syntax: AccessModifier Datatype PropertyName { get { return
DataFieldName; } }
What is Write only Property in C#?
The write-only property is used to write the data into the data field of a class.
Using this property you cannot read the data from the data field. This
property will contain only one accessor i.e. set accessor.
Syntax: AccessModifier Datatype PropertyName {
set { DataFieldName = value; } }
What is Read Write Property in C#?
The Read-Write property is used for both read the data from the data field as
well as write the data into the data field. This property will contain two
accessor i.e. set and get.
Syntax:
AccessModifier DataType PropertyName
}
NOTE: Whenever we create a property, the data type of the property must
be the same as the data type of the data field for which we create the
property. A property can never accept any arguments.
Let’s see an example to understand the Read and Write property.
namespace PropertyDemo
set
_empid = value;
get
{
return _empid;
set
_eage = value;
get
return _eage;
set
_ename = value;
get
{
return _ename;
set
_eaddress = value;
get
return _eaddress;
class Program
obj1.empid = 101;
obj1.ename = "pranaya";
obj1.eage = 27;
obj1.eaddress = "bbsr";
Console.ReadKey();
OUTPUT:
In the above example, we declare the data fields of class Example as private.
As a result, these data fields are not accessible directly from outside the
class Example. So, here from the Program class, we transferred the data into
the data field with the help of properties. As we are providing the abstraction
to the data fields, this is known as data abstraction. So properties will
provide data abstraction.
Let us see an example to understand the Read-Only and Write-Only
Properties in C#.
namespace PropertyDemo
set
num1 = value;
set
num2 = value;
get
return result;
}
}
class Program
{
Example obj1 = new Example();
obj1.setnum1 = int.Parse(Console.ReadLine());
obj1.setnum2 = int.Parse(Console.ReadLine());
obj1.add();
obj1.sub();
obj1.mul();
obj1.div();
Console.ReadKey();
OUTPUT:
}
In the above example, property empid is declared as public. So, the set and
get accessor will be public. If the property is private then the set and get will
be private.
What are symmetric and asymmetric accessors in C#?
If the accessibility modifier of the accessors (both get and set) are the same
within a property then the accessors are known as symmetric accessors. On
the other hand, if the accessibility modifier of the accessors is not the same
within a property then the accessors are known as asymmetric accessors.
For example:
public int empid
In the above example, the set accessor is declared as protected while the
get is public, so they are known as asymmetric. In general asymmetric
accessors are used in the inheritance process.
We can also write the Read-only property using two accessors like
public int empid
We can also write the Write only property using two accessors like
public int empid
}
What are Auto-Implemented Properties in C#?
If you do not have any additional logic while setting and getting the data
from a data field then you can make use of the auto-implemented properties
which was introduced in C# 3.0
The Auto-implemented property reduces the amount of code that we have to
write. When we use auto-implemented properties, the C# compiler implicitly
creates a private, anonymous field behind the scene which is going to
hold the data.
Syntax: Access specifier Datatype Property name { get; set; }
Example: public int A { Get; Set; }
Let’s see an example to understand auto implemented properties in
C#.
namespace PropertyDemo
class Test
return A + B;
}
class Program
obj.A = 100;
obj.B = 200;
Console.WriteLine(obj.Add());
Console.ReadKey();
OUTPUT: 300
Why do we need properties in real-time applications?
Declaring the class fields as public and exposing those fields to the outside
class is bad as we do not have any control over what gets assigned and
returned.
Let’s understand this with one example.
namespace PropertyDemo
class Program
s.ID = -100;
s.Name = null;
s.PassMark = 0;
Console.ReadKey();
OUTPUT:
if (ID < 0)
this._iD = ID;
return this._iD;
{
if (string.IsNullOrEmpty(Name))
this._name = Name;
if (string.IsNullOrEmpty(_name))
return this._name;
return this._passMark;
class Program
S.SetID(101);
S.SetName("Pranaya");
Console.ReadKey();
OUTPUT:
set
if (value < 0)
this._id = value;
get
return this._id;
set
if (string.IsNullOrEmpty(value))
this._name = value;
get
get
return this._passMark;
class Program
S.ID = 101;
S.Name = "Pranaya";
Console.ReadKey();
OUTPUT:
In the above example the Number.ToString() method will give you the
string representation of the integer 100. If you have a complex type let say
Employee class as shown in the example below and when you call
the ToString() method, then you will not get the output as expected. Hence
we have to override the ToString() method, which is inherited from
the Object class.
namespace UnderstandingObjectClassMethods
{
public class Program
{
public static void Main()
{
Employee emp = new Employee();
emp.FirstName = "Pranaya";
emp.LastName = "Rout";
Console.WriteLine(emp.ToString());
Console.ReadKey();
}
}
public class Employee
{
public string FirstName;
public string LastName;
}
}
When you run the above code it will give us the below output
Our requirement is when we call the ToString() method it should display
the First Name and Last Name of the Employee. To achieve this we need
to override the ToString() method which is provided by the Object class.
Modifying the ToString() Method:
Please modify the code as shown below to override the ToString() method.
namespace UnderstandingObjectClassMethods
{
public class Program
{
public static void Main()
{
Employee emp = new Employee();
emp.FirstName = "Pranaya";
emp.LastName = "Rout";
Console.WriteLine(emp.ToString());
Console.ReadKey();
}
}
public class Employee
{
public string FirstName;
public string LastName;
public override string ToString()
{
return FirstName + ", " + LastName;
}
}
}
Now run the application and you will see the First Name and Last Name of
the employee as expected as shown below.
In the following example, the == operator returns False. This makes sense
because C1 and C2 are referring to different objects. However,
the Equals() method returns false, in spite of the values across C1 and C2
being the same. Hence, it makes sense to override, the Equals() method to
return true when the values across the objects are the same.
namespace UnderstandingObjectClassMethods
{
public class Program
{
public static void Main()
{
Customer C1 = new Customer();
C1.FirstName = "Pranaya";
C1.LastName = "Rout";
Customer C2 = new Customer();
C2.FirstName = "Pranaya";
C2.LastName = "Rout";
Console.WriteLine(C1 == C2);
Console.WriteLine(C1.Equals(C2));
Console.ReadKey();
}
}
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Customer C1 = null;
C1.ToString();
Console.ReadLine();
When you run the application, it will give you the following error
This is because the ToString() method in C# expects the object to be not
NULL on which it is invoking. In our example the object C1 is Null and we
are invoking the ToString() on the NULL object, so it gives NULL
Reference exception.
Let see another example.
namespace UnderstandingToStringMethod
Name.ToString();
Console.ReadLine();
}
When we execute the above program, it also gives us the same NULL
Reference exception as shown below.
This is because the Name variable is Null and we are invoking the ToString()
method. Let see what happens when we use
the Convert.Tostring() method with the above two examples.
namespace UnderstandingObjectClassMethods
Customer C1 = null;
Convert.ToString(C1);
Convert.ToString(Name);
Console.WriteLine("No Error");
Console.ReadLine();
}
}
}
Now, with the above changes, run the application and it should be executed
without any error. So in short, the Convert.ToString() method handles null,
while the ToString() method doesn’t handle the Null and throws an
exception. So it’s always a good programming practice to use
the Convert.ToString() method will take care of the Null values and it is
also safe to use.
class Program
Console.WriteLine(int.MaxValue);
Console.ReadLine();
Output: 2147483647
Example without Checked Keyword:
Now, let’s see where the checked keyword can help us in making your code
more useful. In the following example, you can see that we have three
integer variables. The integer variables a and b holds the maximum value
that an integer can hold. Then we just simply add the integer a and b and
stored it in the third integer variable i.e. c.
using System;
namespace CheckedUncheckedDemo
class Program
int a = 2147483647;
int b= 2147483647;
int c = a + b;
Console.WriteLine(c);
Console.ReadLine();
}
Now run the application and see the output.
Output: -2
As you can see it display -2, but this is we were not expecting. What we
except is some error (overflow) or exception. This is where the Checked
keyword helps us to achieve and throws overflow exception.
Example: Using Checked Keyword
The code example uses checked keyword. As we use the checked keyword, it
should throws runtime exception rather than displaying -2.
using System;
namespace CheckedUncheckedDemo
class Program
int a = 2147483647;
int b= 2147483647;
Console.WriteLine(c);
Console.ReadLine();
Now, when you run the application, you should get the following
OverflowException as expected.
In simple words, we can say that the checked keyword is used in scenarios
where you want to ensure that your left hand side data type is not getting
overflow
Unchecked keyword in C#:
Let us understand the need and use of unchecked keyword in C#. The
unchecked keyword behaves almost the same way as the default behavior of
the compiler.
Let’s prove that the above point. So, modify the Program class as shown
below and then see the output.
using System;
namespace CheckedUncheckedDemo
class Program
{
int a = 2147483647;
int b= 2147483647;
Console.WriteLine(c);
Console.ReadLine();
As shown in the above code, we have have just added the unchecked
keyword in front of the arithmetic expression of the c variable. Now, run your
application and you should get the following output..
Output: -2
So this proves that the unchecked keyword works almost the same way as
the default compiler works. Now the question that should comes to your
mind is, when the default compiler works same as unchecked keyword then
what is the exact use of it.
Now, let’s see a simple example to understand the exact need of unchecked
keyword in C#. Please modify the Program class as shown below.
using System;
namespace CheckedUncheckedDemo
class Program
Console.WriteLine(c);
Console.ReadLine();
As you can see in the above code that we have declared variable a and b as
const int. now, when you try to compile the project, you should get the
following compile time error.
If you want to bypass this behavior then you need to use the unchecked
keyword in C#. Please modify the Program class as shown below which will
help you to achieve this task.
using System;
namespace CheckedUncheckedDemo
class Program
Console.WriteLine(c);
Console.ReadLine();
}
Now, when you compile this code you will see that the compiler doesn’t
throw any error like below diagram.
As you can see in the above image, the SomeMethod having three
statements, let’s understand statement by statement how things are
executed internally.
Statement1:
When the first statement is executed, the compiler allocates some memory
in the stack. The stack memory is responsible for keeping track of the
running memory needed in your application. For better understanding,
please have a look at the following image.
Statement2:
When the second statement is executed, it stacks this memory allocation
(memory allocation for variable y) on top of the first memory allocation
(memory allocation for variable x). You can think about the stack as a series
of plates or dishes put on top of each other. Please have a look at the
following diagram for a better understanding.
The Stack Memory allocation and de-allocation in .NET are done using the
Last In First Out principle. In other words, we can say that the memory
allocation and de-allocation are done only at one end of the memory, i.e., the
top of the stack.
Statement3:
In the 3rd statement, we have created an object of SomeClass. When the
3rd statement is executed, it internally creates a pointer on the stack memory
and the actual object is stored in a different memory location called Heap
memory. The heap memory location does not track running memory. Heap is
used for dynamic memory allocation. For better understanding please have a
look at the below image.
It will not de-allocate the heap memory. Later, the heap memory will be de-
allocated by the garbage collector. Now you may have one question in your
mind is why two types of memory, can’t we just allocate everything on just
one memory type?
Why do we have two types of memory?
As we know, in C#, the primitive data types such as int, double, bool, etc.
they just hold a single value. On the other hand, the reference data types or
object data types are complex i.e. an object data type or reference data type
can have reference to other objects as well as other primitive data types.
So, the reference data type holds references to other multiple values, and
each one of them must be stored in memory. Object types need dynamic
memory while primitive data types need static memory. Please have a look
at the following image for a better understanding.
In this case, when you change one of them, the other object is also gets
affected. These kinds of data types are termed as ‘Reference types’ in .NET.
So, class, interface, object, string, and delegate are the example of
Reference Types.
How is the heap memory freed up?
The memory allocation which is done on the stack is gone when the control
moves out from the method i.e once the method completes its execution. On
the other hand, the memory allocation which is done on the heap needs to
be de-allocated by the garbage collector.
When an object stored on the heap is no longer use, that means the object
does not have any reference pointing, then the object is eligible for garbage
collection. At some point in time, the garbage collector will de-allocate this
object from the heap.