0% found this document useful (0 votes)
26 views29 pages

C# Unit 2

The document provides an overview of variables, data types, and operators in C#. It explains the syntax for declaring variables, the rules for naming them, and the different types of data types available, including value, reference, and pointer types. Additionally, it covers various operators such as arithmetic, relational, logical, and assignment operators, along with examples of their usage.

Uploaded by

monalisa1190119
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views29 pages

C# Unit 2

The document provides an overview of variables, data types, and operators in C#. It explains the syntax for declaring variables, the rules for naming them, and the different types of data types available, including value, reference, and pointer types. Additionally, it covers various operators such as arithmetic, relational, logical, and assignment operators, along with examples of their usage.

Uploaded by

monalisa1190119
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT-II

1. VARIABLES:
- In C#, Variables will represent a storage location and each variable has a particular type that determines what type
of values can be stored in the variable.
- C# is a Strongly Typed programming language so before we perform any operation on variables, it’s mandatory to
define a variable with required data type to indicate what type of data that variable can hold in our application.
- Following is the syntax of declaring and initializing a variable in C# programming language.
[Data Type] [Variable Name];
[Data Type] [Variable Name] = [Value];

[Access Specifier] [Data Type] [Variable Name] = [Value];

- If you observe above syntax, we added a required data type before the variable name to tell the compiler about
what type of data the variable can hold or which data type the variable belongs to.
- [Data Type] - It’s a type of data the variable can hold such as integer, string, decimal, etc.
[Variable Name] - It’s a name of the variable to hold the values in our application. [Value] -
Assigning a required value to the variable.
[Access Specifier] - It is used to define an access permission for the variable.

• C# Variables Declaration Example


using System;
namespace klebca
{ class Program
{ static void Main(string[] args)
{ int number = 10;
string name = "Suresh Dasari";
double percentage = 10.23; char gender = 'M';
bool isVerified = true;

Console.WriteLine("Id: " + number);


Console.WriteLine("Name: " + name);
Console.WriteLine("Percentage: " + percentage);
Console.WriteLine("Gender: " + gender);
Console.WriteLine("Verified: " + isVerified); Console.ReadLine(); }
}
}
• Rules to Declare a C# Variables:
- Before we declare and define a variable in C# programming language, we need to follow particular rules.
i. We can define a variable name with the combination of alphabets, numbers and
underscore. ii. A variable name must always start with either alphabets or underscore but not
with numbers.
iii. While defining the variable, no white space is allowed within the variable name. iv.
We should not use any reserve keywords such as int, float, char, etc. for variable name.
v. In c#, once the variable is declared with a particular data type, it cannot be re-declared with a
new type and we shouldn’t assign a value that is not compatible with the declared type.

- Following are the some of valid ways to define the variable names in c# programming language. int abc;
float a2b;
char _abc;

- Following are the some of Invalid ways of defining the variable names in C# programming language.
int a b c; float 2abc;
char &abc; double
int;
• C# Multiple and Multi Line Variables Declaration:
- In c#, we can declare and initialize a multiple variables of same data type in a single line by separating with a
comma.
- Following is the example of defining the multiple variables of same data type in a single line by separating with
a comma in C# programming language.
int a, b, c;
float x, y, z = 10.5;

• C# Variables Assignment:
- In c#, once we declare and assign a value to the variable that can be assigned to another variable of same
data type.

- Following is the example of assigning a value of one variable to another variable of same type in C#
programming language.
int a = 123; int b = a;
string name = "suresh"; string firstname = name;
- In c#, it’s mandatory to assign a value to the variable before we use it otherwise we will get a compile time
errors.
- In case, if we try to assign a value of string data type to integer data type or vice versa like as shown below,
we will get an error like “cannot implicitly convert type int to string”.
int a = 123; string name = a;

2. C# Data Types:
- In C# programming language, Data Types are used to define a type of data the variable can hold such as
integer, float, string, etc. in our application.
- C# is a Strongly Typed programming language so before we perform any operation on variables, it’s
mandatory to define a variable with required data type to indicate what type of data that variable can hold in
our application.

- Syntax of Defining C# Data Types [Data Type] [Variable Name];


[Data Type] [Variable Name] = [Value];

- If you observe above syntax, we added a required data type before variable name to tell compiler about what
type of data the variable can hold or which data type the variable belongs to.
[Data Type] - It’s a type of data the variable can hold such as integer, string, decimal, etc.
[Variable Name] - It’s a name of the variable to hold the values in our application. [Value] -
Assigning a required value to the variable.

- Example:

namespace KLEBCA
{ class Program
{ static void Main(string[] args)
{ int number = 10;
string name = "Suresh Dasari"; double percentage = 10.23; char gender = 'M'; bool
isVerified = true;
}
}
}

- If you observe above c# data types example, we defined multiple variables with different data types based on
our requirements.

• Different Data Types in C#:

- In C# programming language, we have a 3 different type of data types, those are

Type Data Types


Value Data Type int, bool, char,
double, float,
etc.
Reference Data Type string, class, object,
interface,
delegate, etc.
Pointer Data Type Pointers.

- Following diagram will illustrate more detail about different data types in c# programming language.
• C# Value Data Types:
- In c#, the Value Data Types will directly store the variable value in memory. In c#, the value data types will
accept both signed and unsigned literals.
- Following table lists the value data types in c# programming language with memory size and range of values.

Data Type .NET Type Size Range

byte Byte 8 bits 0 to 255

sbyte SByte 8 bits -128 to 127

int Int32 32 bits -2,147,483,648 to


2,147,483,647
Uint UInt32 32 bits 0 to 4294967295

Short Int16 16 bits -32,768 to 32,767

Ushort UInt16 16 bits 0 to 65,535

Long Int64 64 bits -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
Ulong UInt64 64 bits 0 to
18 ,446,744,073,709,551,
61 5
Float Single 32 bits -3.402823e38 to 3.402823e38

Double Double 64 bits -1.79769313486232e308 to


1.79769313486232e308
Bool Boolean 8 bits True or False

Decimal Decimal 128 bits (+ or -)1.0 x 10e-28 to 7.9 x


10e28
DateTime DateTime - 0:00:00am 1/1/01 to
11:59:59pm 12/31/9999

C# Reference Data Types:


In c#, the Reference Data Types will contain a memory address of variable value because the
reference types won’t store the variable value directly in memory.
C# Pointer Data Types:
In c#, the Pointer Data Types will contain a memory address of variable value. To get the pointer details we have
a two symbols ampersand (&) and asterisk (*) in C# language.

Following is the syntax of declaring the pointer type in C# programming language.


type* test;

Symbol Name Description


& Address It's useful to determine the
Operator address of a variable
* Indirection It's useful to access the
Operator value of an address.

3. C# keywords:

- In c#, Keywords are the predefined set of reserved words that have special meaning for the compiler.
- So the keywords in C# cannot be used as an identifiers such as variable name, class name, etc. in our
applications.
- C# Use Keywords as Variable Names: In case, if you want to use Keywords as variable names (identifiers),
then you need to include @ as a prefix for your variable names.

- For example, @switch is a valid identifier but switch is not because it’s a keyword and having a special
meaning for the compiler.

- Following is the example of using the reserve keywords as variable names by including @ as a prefix in C#
programming language.

using System;

namespace CsharpExamples
{ public class @class
{ public int age;
}

class Program
{ static void Main(string[] args)
{

@class p1 = new @class(); p1.age = 10;


Console.WriteLine("Age: "+p1.age);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
}

4. C# Operators (Arithmetic, Relational, Logical, Assignment, Precedence):

- In c#, Operator is a programming element that specifies what kind of an operation need to perform on
operands or variables.
- For example, an addition (+) operator in C# is used to perform the sum operation on operands.

- In c#, we have a different type of operators available, those are

- These operators are categorized as a different group such as Binary Operators, Unary Operators and Ternary
Operators based on taking the number operands to perform the operations.
- Suppose, if operator that takes a one operand to perform the operation such as precedence operator (++), then
those will call as a Unary Operators.

- In case, if operator that takes a two operands to perform the operation such as arithmetic operator (-, +, *, /),
then those will call as a Binary Operators and we have a Ternary Operator that takes three operands to perform
the operation, such as conditional operator (?:).

C# Arithmetic Operators with Example:


- In c#, Arithmetic Operators are used to perform basic arithmetic calculations like addition, subtraction, division,
etc. based on our requirements.
- For example, we have an integer variables x = 20, y = 10 and if we apply an arithmetic operator + (x + y) to
perform an addition operator, then we will get the result as 30.
- Following table lists the different type of operators available in c# arithmetic operators.

- Example:
using System; namespace
KLEBCA
{ class Program
{ static void Main(string[] args)
{ int result;
int x = 20, y = 10; result = (x + y);

Console.WriteLine("Addition Operator: " + result); result = (x - y);


Console.WriteLine("Subtraction Operator: " + result); result = (x * y);
Console.WriteLine("Multiplication Operator: "+ result); result = (x / y);
Console.WriteLine("Division Operator: " + result); result = (x % y);
Console.WriteLine("Modulo Operator: " + result); Console.WriteLine("Press Enter Key to
Exit..");
Console.ReadLine();
}
}
}

Relational Operators:
- Relational operators are used for comparison purpose in conditional statements.
- C# has following relational operators:

Operand Description
== Equality check
!= Un-equality check
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

- Example:
class Program
{ static void Main(string[] args)
{ bool result;
int x = 10, y = 20; result = (x == y);
Console.WriteLine("Equal to Operator: " + result); result = (x > y);
Console.WriteLine("Greater than Operator: " + result); result = (x <= y);
Console.WriteLine("Lesser than or Equal to: "+ result); result = (x != y);
Console.WriteLine("Not Equal to Operator: " + result); Console.WriteLine("Press Enter Key to
Exit..");
Console.ReadLine();

}
}

Logical and Bitwise Operator:


- These operators are used for logical and bitwise calculations.
- C# contains following logical and bitwise operator:

Operand Description
& Bitwise AND
Bitwise OR
Bitwise XOR
! Bitwise NOT
&& “Logical” or “short circuit”
AND
“Logical” or “short circuit”
OR

- If we use Logical AND, OR operators in c# applications, those will return the result like as shown below for
different inputs.
- If you observe above table, if any one operand value become false, then the logical AND operator will return false,
same way the logical OR operator will return true, if any one operand value become true.

- Some examples of the usage of logical expression are:


1. If (age>55 && salary<1000), give increment.
2. If (number <0|| number >100),stop

Assignment Operators:
- Assignment operators are use to assign values to variables.
- For example, we can declare and assign a value to the variable using assignment operator (=) like as shown below.
int a; a = 10;

- Some common assignment operators in C# are:

Operand Description
= Simple assignment
+= Subtractive assignment
-= Multiplicative assignment
*= Division assignment
/= Division assignment
%= Modulo assignment

INCREMENT AND DECREMENT OPERATORS:

i. Postfix Operator:
- The increment operator ++ if used as prefix on a variable, the value of variable gets incremented by 1.
- After that the value is returned unlike Postfix operator.
- It is called Prefix increment operator. In the same way the prefix decrement operator works but it
decrements by 1.
Example:

using System; class Program


{ static void Main()
{ int a, b; a = 50;
Console.WriteLine(++a); b = a;
Console.WriteLine(a);
Console.WriteLine(b);
}
}

output 51
51
51

ii. Postfix Operator:


- The increment operator ++ if used as postfix on a variable, the value of variable is first returned and then
gets incremented by 1.
- It is called Postfix increment operator.
- In the same way the decrement operator works but it decrements by 1.

using System;

class Program
{ static void Main()
{ int a, b; a = 10;
Console.WriteLine(a++);
b = a; Console.WriteLine(a); Console.WriteLine(b); }
}

Output:
10
11
12

Conditional Operators (Ternary Operator):


- Ternary operator is a Conditional operator in C#. It takes three arguments and evaluates a Boolean
expression.

- For example − b = (a == 1) ? 20 : 30;


- Above, if the first operand evaluates to true (1), the second operand is evaluated. If the first operand
evaluates to false (0), the third operand is evaluated.

- Example:

using System;
namespace DEMO
{ class Program
{ static void Main(string[] args)
{ int a, b; a = 10;
b = (a == 1) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b); b = (a ==
10) ? 20 : 30;
Console.WriteLine("Value of b is {0}", b); Console.ReadLine();
}
}
}

Output:
Value of b is 30 Value of b is 20

Operators Precedence:

- In c#, Operators Precedence is used to define a multiple operators in single expression and the evaluation of
expression can be happened based on the priority of operators.
- For example, the multiplication operator (*) is having a higher precedence than the addition operator (+).
- So if we use both multiplication (*) and addition (+) operators in single expression, first it will evaluate the
multiplication part and then the addition part in expression.
int i = 3 + 4 * 5;

- When we execute above statement, first the multiplication part (4 * 5) will be evaluated.
- After that the addition part (3 + 12) will be executed and i value will become a 23.

- As said earlier, multiplication (*) operator is having a higher precedence than addition (+) operator so first
multiplication part will be executed.

 Flow Control
– Looping in a programming language is a way to execute a statement or a set of statements multiple times
depending on the result of the condition to be evaluated to execute statements.
– The result condition should be true to execute statements within loops.
– Loops are mainly divided into two categories:
1. while loop:
- The test condition is given in the
beginning of the loop and all
statements are executed till the
given boolean condition satisfies
when the condition becomes false,
the control will be out from the
while loop.
- Syntax: while (boolean condition)
{ loop statements...
}

2. for loop:
- for loop has similar functionality as while loop but with different syntax. for loops are preferred when
the number of times loop statements are to be executed is known beforehand.
- The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is
done in one line in for loop thereby providing a shorter, easy to debug structure of looping.
- Syntax:
for (loop variable initialization ; testing condition; increment / decrement) {
// statements to be executed
}

1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is
the starting point of for loop. An already declared variable can be used or a variable can be declared,
local to loop only.

2. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit
condition for a loop. It must return a boolean value true or false. When the condition became false the
control will be out from the loop and for loop ends.

3. Increment / Decrement: The loop variable is incremented/decremented according to the requirement


and the control then shifts to the testing condition again.

3. do-while loop:
- do while loop is similar to while loop with the only difference that it checks the condition after
executing the statements, i.e it will execute the loop body one time for sure because it checks the
condition after executing the statements.
- Syntax : do
{ statements..
}while (condition);

 Conditional Statements
– Decision Making in programming is similar to decision making in real life.
– In programming too, a certain block of code needs to be executed when some condition is fulfilled.
– A programming language uses control statements to control the flow of execution of program based on
certain conditions.
– These are used to cause the flow of execution to advance and branch based on changes to the state of a
program.

– The conditional statements of C#:


o if o if-else o
if-else-if o
Nested if o
Switch
o Nested switch

1. IF Statement
- The if statement checks the given condition. If the condition evaluates to be true then the block of
code/statements will execute otherwise not.
- Syntax:

if(condition)
{
//code to be executed }
– Note: If the curly brackets { } are not used with if statements than the statement just next to it is only
considered associated with the if statement.
– Example:
if (condition) statement 1;
statement 2;
– In this example, only statement 1 is considered to be associated with the if statement.

2. IF – else Statement
- The if statement evaluates the code if the condition is true but what if the condition is not true, here
comes the else statement.
- It tells the code what to do when the if condition is false.
- Syntax: if(condition)
{
// code if condition is true
} else
{
// code if condition is false }

3. Nested If-Else Statement


- When series of decision are involved, need to use more than one if..else statement in nested
form as follows: if(condition)
{
if(condition)
{
//true statement
}
else
{
//false statement
}
} else
{
//main false statement
}
- When nesting, care should be taken to match every if with an else.

4. Switch Statement
- Switch statement is an alternative to long if-else-if ladders.
- The expression is checked for different cases and the one match is executed.
- break statement is used to move out of the switch.
- If the break is not used, the control will flow to all cases below it until break is found or switch comes to an
end.
- There is default case (optional) at the end of switch, if none of the case matches then default case is
executed.
- Syntax:
switch (expression)
{ case value1: // statement sequence break;
case value2: // statement sequence break;
.
.
.
case valueN: // statement sequence break;
default: // default statement sequence
}
Object And Classes: In c#, Classes and Objects are interrelated. The class in c# is
nothing but a collection of various data members (fields, properties, etc.) and member
functions. The object in c# is an instance of a class to access the defined properties and
methods.

Class: In c#, Class is a data structure and it will combine a various types of data
members such as fields, properties, member functions and events into a single unit.

Declaring a Class in C#:In c#, classes are declared by using class keyword. Following is the
declaration of class in c# programming language.

public class users {

// Properties, Methods, Events, etc.

If you observe above syntax, we defined a class “users” using class keyword with public access
modifier. Here, the public access specifier will allow the users to create an objects for this class
and inside of the body class, we can create a required fields, properties, methods and events to
use it in our applications.

C# Class Example:
If you observe above image, we used a various data members like access modifiers, fields,
properties, methods, constructors, etc. in our c# class based on our requirements.

C# Class Members:

C# Object:

Generally, we can say that objects are the concrete entities of classes. In c#, we can create an
objects by using a new keyword followed by the name of the class like as shown below.

Users user = new Users();

If you observe above example, we created an instance (user) for the class (Users) which we
created in previous section. Now the instance “user” is a reference to an object that is based on
Users. By using object name “user” we can access all the data members and member functions
of Users class.
Object Example:

class Program

{
static void Main(string[] args)
{
Users user = new Users("Suresh Dasari", 30);
user.GetUserDetails();
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}
public class Users
{
public string Name { get; set; }
public int Age { get; set; }
public Users(string name, int age)
{
Name = name;
Age = age;
}
public void GetUserDetails()
{
Console.WriteLine("Name: {0}, Age: {1}", Name, Age);
}
}

If you observe above example, we created a new class called “Users” with a required data
members and member functions. To access Users class methods and properties, we created an
object (user) for Users class and performing required operations.

When we execute above c# program, we will get the result like as shown below.

ACCESS MODIFIERS:
Access Modifiers are the keywords which are used to define an accessibility level for all types and type
members.
By specifying an access level for all types and type members, we can control that whether they can be
accessed in other classes or in current assembly or in other assemblies based on our requirements.

Following are the different type of access modifiers available in c# programming language.

 Public
 Private
 Protected
 Internal
Properties (GET, SET):

In c#, Property is an extension of class variable and it provides a mechanism to read, write or
change the value of class variable without effecting the external way of accessing it in our
applications.

In c#, properties can contain one or two code blocks called accessors and those are called a get
accessor and set accessor. By using get and set accessors, we can change the internal
implementation of class variables and expose it without effecting the external way of accessing
it based on our requirements.

Generally, in object oriented programming languages like c# we need to define a fields as private,
and then use properties to access their values in public way with get and set accessors.

Following is the syntax of defining a property with get and set accessor in c# programming
language.

<access_modifier> <return_type> <property_name>


{
get
{
// return property value
}
set

{
// set a new value
}
}

Static Member of the class

C# classes, variables, methods, properties, operators, events, and


constructors can be defined as static using the static modifier keyword.

Static Methods

You can define one or more static methods in a non-static class. Static
methods can be called without creating an object. You cannot call static
methods using an object of the non-static class.

The static methods can only call other static methods and access static
members. You cannot access non-static members of the class in the static
methods.

Example: Static Method

class Program
{
static int counter = 0;
string name = "Demo Program";

static void Main(string[] args)


{
counter++; // can access static fields
Display("Hello World!"); // can call static methods
name = "New Demo Program";
//Error: cannot access non-static members

SetRootFolder("C:\MyProgram");
//Error: cannot call non-static method
}

static void Display(string text)


{
Console.WriteLine(text);
}

public void SetRootFolder(string path) { }


}

Rules for Static Methods

1. Static methods can be defined using the static keyword before areturn
type and after an access modifier.
2. Static methods can be overloaded but cannot be overridden.
3. Static methods can contain local static variables.
4. Static methods cannot access or call non-static variables unless theyare
explicitly passed as parameters.

Constructor in C#:

In c#, Constructor is a method which will invoke automatically whenever an instance of class or
struct is created. The constructor will have a same name as the class or struct and it useful to
initialize and set a default values for the data members of the new object.

In case, if we create a class without having any constructor, then the compiler will automatically
create a one default constructor for that class. So, there is always one constructor will exist in
every class.

In c#, a class can contain more than one constructor with different type of arguments and the
constructors will never return anything, so we don’t need to use any return type, not even void
while defining the constructor method in class.

SYNTAX:

As discussed, constructor is a method and it won’t contain any return type. If we want to create
a constructor in c#, then we need to create a method whose name is same as the class name.

public class User


{
// Constructor
public User()
{
// Your Custom Code
}
}
If you observe above syntax, we created a class called “User” and a method whose name is
same as class name. Here the method User() will become a constructor of our class.

In c#, we have a different type of constructors available, those are


 Default Constructor

 Parameterized Constructor
 Copy Constructor
 Static Constructor
 Private Constructor

Default Constructor: In c#, if we create a constructor without having any parameters, then we
will call it as default constructor and the every instance of class will be initialized without any
parameter values.

Parameterized Constructor: In c#, if we create a constructor with at least one parameter, then
we will call it as parameterized constructor and the every instance of class will be initialized with
parameter values.

Example for parameterized Constructor:

class User
{
public string name, location;
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}
class Program
{
static void Main(string[] args)
{
// The constructor will be called automatically once the
instance of class created
User user = new User("Suresh Dasari", "Hyderabad");
Console.WriteLine(user.name);
Console.WriteLine(user.location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}

If you observe above example, we created a class called “User” and the constructor method
“User(string, string)” with parameters. When we create an instance of our class (User) with
required parameters, then automatically our constructor method will be called.

When we execute above c# program, we will get the result like as shown below.

If you observe above result, our constructor method has called automatically and initialized the
parameter values after creating an instance of our class with required parameters.

Constructor Overloading:

In c#, we can overload the constructor by creating another constructor with same method
name but with different parameters.

Example:

using System;

namespace Tutlane
{
class User
{
public string name, location;
// Default Constructor
public User() {
name = "Suresh Dasari";
location = "Hyderabad";
}
// Parameterized Constructor
public User(string a, string b)
{
name = a;
location = b;
}
}
class Program
{
static void Main(string[] args)
{
User user = new User(); // Default Constructor will be called
User user1 = new User("Rohini Alavala", "Guntur"); //
Parameterized Constructor will be called
Console.WriteLine(user.name + ", " + user.location);
Console.WriteLine(user1.name + ", " + user1.location);
Console.WriteLine("\nPress Enter Key to Exit..");

Console.ReadLine();
}
}
}
If you observe above example, we created a class called “User” and overloaded a constructor
“User()” by creating another constructor “User(string, string)” with same name but with different
parameters.

When we execute above c# program, we will get the result like as shown below.

If you observe above result, the respective constructor methods will be called automatically when we
create an instance of our class with or without parameters based on our requirements.

Copy Constructor: In c#, Copy Constructor is a parameterized constructor which contains a


parameter of same class type. The copy constructor in c# is useful whenever we want to initialize
a new instance to the values of an existing instance.

In simple words, we can say copy constructor is a constructor which copies a data of one object
into another object. Generally, c# won’t provide a copy constructor for objects but we can
implement ourselves based on our requirements.

Static Constructor:
In c#, Static Constructor is used to perform a particular action only once throughout the
application. If we declare a constructor as static, then it will be invoked only once irrespective of
number of class instances and it will be called automatically before the first instance is created.

following are the properties of static constructor in c# programming language.

 Static constructor in c# won’t accept any parameters and access modifiers.


 The static constructor will invoke automatically, whenever we create a first instance of
class.
 The static constructor will be invoked by CLR so we don’t have a control on static
constructor execution order in c#.
 In c#, only one static constructor is allowed to create.

using System;

namespace Tutlane
{
class User
{
// Static Constructor
static User()
{
Console.WriteLine("I am Static Constructor");
}
// Default Constructor
public User()
{
Console.WriteLine("I am Default Constructor");
}
}
class Program
{
static void Main(string[] args)
{
// Both Static and Default constructors will invoke for first
instance
User user = new User();
// Only Default constructor will invoke
User user1 = new User();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}

If you observe above result, for the first instance of class both static and default constructors
execute and for the second instance of class only default constructor has executed.

This is how we can use static constructor in c# programming language to execute particular
action only once throughout the application based on our requirements.

Private Constructor:

In c#, Private Constructor is a special instance constructor and it is used in a classes that
contains only static members. If a class contains one or more private constructors and no public
constructors, then the other classes are not allowed to create an instance for that particular class
except nested classes.

Constructors are special methods called when a class is instantiated.

 Constructor will not return anything.


 Constructor name is same as class name.
 By default C# will create default constructor internally.Constructor with no arguments and no body is called
default constructor.
 Constructor with arguments is called parameterized constructor.
 Constructor by default public.
 We can create private constructors.
 A method with same name as class name is called constructor there is no separate keyword.

Destructors
.Net will clean up the un-used objects by using garbage collection process. It internally uses the
destruction method to clean up the un-used objects. Some times the programmer needs to do
manual cleanup.

Syntax
~<ClassName>
{}
Sample Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BRK.ConstructorExample
{
class Welcome
{
// Default constructor
public Welcome()
{
Console.WriteLine("Welcome message from Default
Constructor...");
}

// Destructor
~Welcome()
{
Console.WriteLine("Destructor called");
}
}
class Program
{
static void Main(string[] args)
{
// Creating object for Welcome class
// This will called default constructor
Welcome obj = new Welcome();

Console.Read();
}
}
}
Method Overloading: In c#, Method Overloading means defining a multiple methods with
same name but with different parameters. By using Method Overloading, we can perform a
different tasks with same method name by passing different parameters.

Suppose, if we want to overload a method in c#, then we need to define another method with
same name but with different signatures. In c#, the Method Overloading is also called as
compile time polymorphism or early binding.

Example:

using System;

namespace Tutlane
{
public class Calculate
{
public void AddNumbers(int a, int b)
{
Console.WriteLine("a + b = {0}", a + b);
}
public void AddNumbers(int a, int b, int c)
{
Console.WriteLine("a + b + c = {0}", a + b + c);
}
}
class Program
{
static void Main(string[] args)
{
Calculate c = new Calculate();
c.AddNumbers(1, 2);
c.AddNumbers(1, 2, 3);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}
C# .NET

JAIN COLLEGE OF BBA, BCA AND COMMERCE, BELAGAVI 29

You might also like