Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

CSharp.NET Tutorial – Day 10

Tags: class

In previous article, we have discussed concept of Arrays like what is an array, what are different types of arrays available like what is Single Dimensional, what is two Dimensional, what is jagged Array along with their syntaxes and some examples, what are Array Class methods available like Sort, Reverse, Copy, GetLength, and Length, what is Foreach Loop, what is the difference between for and foreach loop, and what are the different ways of inputting values to a program like through ReadLine method of Console class and through CommandLine Parameters, etc
Please find below the link for accessing the article
CSharp.NET Tutorial - Day 9 

Now, in this article we will discuss how to work with Visual Studio along with some important components like Solution Explorer, etc, what is Namespace, a brief on Object Oriented Programming, what is the drawback in Procedural Programming approach i.e. Security and Reusability of the code, features of object oriented programming like Encapsulation, Abstraction, Inheritance, Polymorphism, what are Subprograms, what are methods, what are Modifiers available like public, private, internal, virtual, static, what are Input parameters and Output parameters, what is difference between passby value and passby reference, what are ref and out keywords, what is Constructor, what are Zero Argument (or) Default Constructors and Parameterized Constructors, what is Static, what are Non-static (or) Instance Methods and Static members, what are Instance variables and Static Variables and difference between Instance variables and Static Variables, what are Constant Variables, what are ReadOnly Variables, difference between Constant Variables and ReadOnly Variables, what are Static Methods and Instance Methods, difference between Static Methods and Instance Methods, what are Static Constructors and Instance Constructors, difference between Static Constructors and Instance Constructors, what are Static Classes along with syntaxes and some examplesfor better understanding, etc


Working with Visual Studio

1)      Visual Studio is an Integrated Development Environment (IDE) used for developing.NET applications using any .NET language like C#,VB, etc. and also we can develop any kind of applications like Console Applications, Windows Applications, Web Applications, etc.

2)      In order to open Visual Studio, go to
Start Menu -> Programs -> MS Visual Studio -> MS Visual Studio -> Click On it to open

3)      Applications that we developed under Visual Studio are known as Projects; here project is a collection of various files or items.  To create a project, either click on “New Project” option or select “New Project” under “File Menu”, which will open a New Project window.

4)      Under ‘New Project’ window, we need to specify the following details.
a) In the left hand side, choose the language in which we wish to develop the application
Eg:  Visual C#

b) In the middle, choose the type of application from available templates we wish to develop by selecting a project template.
Eg:  Console Application

c) In the bottom, specify a name to the project.
Eg:  First Project

d) Below Project name, specify the location where this project to be saved.
Eg:  C:\CSharp

e) Click on 'OK' button which will create the project with default class ‘Program’ under the file Program.cs

f) When projects are developed in Visual Studio, by default a ‘namespace’ gets created with same name of the project i.e. FirstProject.

From now on, each and every ‘class’ of the project comes within the same namespace.

Namespace:  A namespace is a logical container of types like Classes, Structures, etc.

g) Now under ‘main’ method of Program class, write the following code.

Console.WriteLine("This Is My First C# Project");
Console.ReadLine();

h) To run the above class, either press F5 (or) Ctrl+F5 (or) click on start Debugging button on top of the studio, which will save compile and then execute the program.

i) Under Visual Studio, we find a window known as ‘Solution Explorer’ on the right side used for organizing the complete application, which allow us to view, add, delete items under the projects.  By default it should be displayed on right side.  If not, we can open ‘Solution Explorer’ by going to ‘View Menu’ and select 'Solution Explorer'.

j) if we want to add a new class under project, we can do it by opening solution explorer right click on Project, select add ‘New Item’, which will open ‘Add New Item’ window, select class template in it, specify a name in the bottom.  Then Click on Add button, which will add the class under project.

Eg:  class1.cs

Note:  The new class added also comes under the same namespace ‘FirstProject’.

k) Now under the new class, write the following code.
static void Main()
{
Console.WriteLine("Second Class");
Console.ReadLine();
}

l) To run the above class, open ‘Solution Explorer’ right click on the ‘Project,’ select ‘Properties,’ which will open project property window, under it we can find an option ‘Startup Object,’ which will list all the classes of project that contains a valid Main Method in them, choose our desired class and run.

This is the basic working structure with Visual Studio.  Now, we will discuss what is object oriented programming and its features one by one.


Object Oriented Programming

Before 70's, the industry was using Procedural programming approach in application development.  Procedural approach does not provide any Security or Reusability of the code.

To overcome this drawback, a new approach in programming came into existence i.e. Object Oriented Programming which will provide both security and reusability.

If a language to be called as Object programming language, it should need to satisfy a set of rules or properties, which will be listed below.
1)      Encapsulation
2)      Abstraction
3)      Inheritance
4)      Polymorphism

1) Encapsulation
As per Encapsulation, if we want to protect anything, it has to be enclosed (or) wrapped under a special container called class.



Class provides the basic security for the content present inside it.

2) Abstraction
Abstraction is all about hiding the complexity behind the logic (or) code and providing the set of interfaces to consume the functionalities.

3) Inheritance
Inheritance provides us reusability of the code.  Using inheritance, we can acquire the properties of an existing class into a new class for consumption.



4) Polymorphism
Basically, entities behave in different ways depending upon the input we provide.  This concept is called as Polymorphism in object oriented programming.



This means whenever the input is changed, the output of the entity also changed.

Subprograms
A subprogram is a named block of code that can be reused.  These sub programs are referred in each language in different forms like functions, methods, subroutines, stored procedures, etc.

Methods
A subprogram in .NET language is referred as a Method, which can be either ‘value returning’ or ‘non-value returning.’  We can define a method as below.

Syntax
[<modifiers>]<void|type><name>([<parameter definitions>])
{
statements
}

-          Modifiers are special keywords like public, private, internal, virtual, static, etc.  These are optional.
-          A method can be either ‘value returning’ or ‘non-value returning.’  Here, we can use ‘void’ to define a ‘non-value returning’ method and we can use particular type in case of a ‘value returning’ method like int, string, etc.
-          We can pass parameters to a method for its execution if required.

We can pass parameters to a method using below process

[ ref | out ] <type> <var> [=value] [,....n]

Here, parameters of a method can be of two types
1) Input parameters
2) Output parameters

Input parameters are used for passing values to a method to execute, whereas output parameters are used for returning values out of the method after execution.

To pass input parameters for a method, we use ‘passby value’ mechanism, whereas for output parameters, we use ‘passby reference’ mechanism (Implicit pointers).

By default, every parameter of a method is an input parameter which uses ‘passby value’ mechanism.  To define an output parameter for a method, use ‘passby reference’ mechanism and the parameter should be prefixed either by using ‘ref’ or ‘out’ keywords.

As per encapsulation, methods should be defined under ‘classes’ and we must create an ‘object’ of class in order to call or invoke that particular method like below.

<class><obj> = new <class> ([<list of values>]);

Eg:
Program p=new Program (); //p is object

or

Program p; //p is variable
p = new Program (); //p is object

Note:  The object of a class can be created within a class or in other classes also.  While creating within a class, we can create it under Main because Main is the entry point of a class.

Open Visual Studio, click new project -> choose the language as Visual C# -> choose the template ‘Console application,’ -> specify the Project name ‘OopsProject’ -> save it in the desired location and click ‘OK.’  Now under the default class Program, write the below code.

class Program
{
//No input and no return type
void Test1() //Static
{
Console.WriteLine("First Method");
Console.WriteLine();
}

//No return type but has input
void Test2(int x, int max) //Dynamic
{
for (int i = 1; i <= max; i++)
Console.WriteLine("{0}*{1}={2}", x, i, x * i);
}

//No input but has return type
string Test3() //Static
{
return "Third Method";
}

//Has input and return type also
string Test4(string name) //Dynamic
{
return "Hello" + name;
}

//Reading default values to Params(4.0)
void AddNums(int x, int y = 50, int z = 25)
{
Console.WriteLine(x + y + z);
}

//Methods with multiple objects
void Math1(int a, int b, ref int c, ref int d)
{
c = a + b;
d = a + b;
}
void Math2(int a, int b, out int c, out int d)
{
c = a - b;
d = a / b;
}

static void Main(string[] args)
{
Program p = new Program();

//Calling non value returning methods
p.Test1();
p.Test2(5, 34);

//Calling value returning methods
string str = p.Test3();
Console.WriteLine(str);
Console.WriteLine(p.Test4("Praveen"));
Console.WriteLine();

//Calling method with default values
p.AddNums(100);
p.AddNums(100, 100);
p.AddNums(100, z: 100);
p.AddNums(100, 100, 100);
Console.WriteLine();

//Calling methods with output parameters
int x = 0;int y = 0; //Initialization is Mandatory
p.Math1(100, 60, ref x, ref y);
Console.WriteLine(x + " " + y);
int q, r; //Intialization is optional
p.Math2(100, 50, out q, out r);
Console.WriteLine(q + " " + r);
Console.ReadLine();
}
}

If a Method is defined with output parameters, the execution of that Method takes place as below

void Math1(int x,int y, ref int a,ref int b)

If any variable is declared using ‘ref’ or ‘out’ keywords, they will be considered as Implicit pointer variables, which contains the address of another variable.  As the pointers are Implicit, which are basically under the control of Garbage collector and manipulating these address values is not possible (Secure).

In C# 4.0, we have been given with a feature of defining parameters to a Method by specifying default values and those default values gets used whenever the method is called without supplying values to the default parameters.

Add a New class in the project naming it as “First.cs” and write the following code.

class First
{
int x = 100;
static void Main()
{
First f; //f is variable
f = new First(); //f is a object
Console.WriteLine(f.x);
Console.ReadLine();
}
}

A variable or method defined within a class is considered as a member of a class and every non static member of a class requires object of the class for initialization or execution.

We can create the object of a class using new operator and we can destroy the object of a class by assigning null to the object.  Once null is assigned to an object, the object gets marked as unused and can't be used anymore for invoking members using that object.

To test this, rewrite the code under Main method of class, “First” as below.

First f = new First();
Console.WriteLine(f.x);
f = null;
Console.WriteLine(f.x); //Invalid Error
Console.ReadLine();

We can create any number of objects to a class and each object we create will have its own memory allocated separately.  Any modification made on a member of an object does not get reflected to members of other object.

To test this, rewrite the code under Main method of class, ‘First’ as below.

First f1 = new First();
First f2 = new First();
Console.WriteLine(f1.x + " " + f2.x);
f1.x = 500;
Console.WriteLine(f1.x + " " + f2.x);
Console.ReadLine();

If required, we can assign the object of a class to the variable of same class also and once the assignment is done, the variable will be called as “reference,” which points to the memory of object which is assigned to it, but will not have separate memory allocation.  So any manipulations performed on the members using that object gets reflected to ‘reference’ members also and vice-versa.

To test this, rewrite the code under Main method of class, ‘First’ as below.

First f1 = new First();
First f2 = f1;
Console.WriteLine(f1.x + " " + f2.x);
f1.x = 500;
Console.WriteLine(f1.x + " " + f2.x);
Console.ReadLine();

When an object and references are consuming the same memory in the context and if null is assigned to that object or reference, it cannot consume the memory.

To check this, rewrite the code under Main method of class, ‘First’ as below.

First f1 = new First();
First f2 = f1;
f1 = null;
Console.WriteLine(f2.x); //valid
Console.WriteLine(f1.x); //Invalid
Console.ReadLine();

Now we will see what will be happened when an “Object” of “Class” is created?
When we create the object of a class, internally following things takes place.

1) Reading the classes:  In this phase, it identifies each and every member that is defined under the class.
2) Invoking the Constructors
3) Allocating the required memory for execution of the class

What is Constructor?
1) Constructor is a special method that is available for every class and it is responsible for initializing the variables of a class.
2) Every class requires a Constructor in it to execute.  Without a constructor, no class will be executed.

Note:  Because Constructors are mandatory for a class to execute when the program is getting compiled.  If the compiler does not find a Constructor in that class, it will take the responsibility of defining a Constructor to the class which is the default constructor for that class.

For example, if we write a class as below

class Test
{
int x;string s;bool b;
}

After compilation, it looks as below
class Test
{
public Test( ) //Constructor
{
x=0; str=null; b=false;
}
}

The Constructor defined by compiler will always be “public.”

A Constructor will have the same name of our class and also they are non-value returning methods.

Syntax to define a Constructor
We can define the Constructor in a class as below.

[<modifiers>] <name> ([<parameter definitions>])
{
statements
}

*Add a class, ‘ConEx.cs’ in the project and write the below code

class ConEx
{
ConEx()
{
Console.WriteLine("Constructor of class");
}
void Ex()
{
Console.WriteLine("Method of class");
}
static void Main()
{
ConEx cd1 = new ConEx();
ConEx cd2 = new ConEx();
ConEx cd3 = cd2;
cd1.Ex(); cd2.Ex(); cd3.Ex();
Console.ReadLine();
}
}

In the above program, each time we create an object of the class, ConEx, it will internally invoke the Constructor of that class, which is then responsible for allocation of the memory required.

There are two types Constructors available
1) Zero Argument (or) Default Constructors
2) Parameterized Constructors

A Constructor without any parameters is called ‘Zero Argument’ or ‘Default’ Constructor, whereas a Constructor with parameters is a Parameterized Constructer.

Parameters can be either input parameters or output parameters.

If a class contains Parameterized Constructors in it, we should send values to the parameters while creating the object of a class.  This is because Constructor call should always match a Constructor signature.

To check this, rewrite the Constructor in above class as below.

ConEx(int x)
{
Console.WriteLine("Constructor of class:"+x);
}

Now if we run the class, we will get an error.  Because our Constructor call does not match the Constructor signature.  To resolve this problem, pass values to the Constructor while creating the object under Main as below.

ConEx cd1=new ConEx(10);
ConEx cd2=new ConEx(20);

Constructors are basically used in a class for initializing variables of a class.  So using a parameterized Constructor, we can send all the initialization values that are required for a class in order to execute.

To test this add a new class, ‘Maths.cs’ in our project and write the below code.

class Maths
{
int x, y; //Class Variables
public Maths(int x, int y) //Block Variables
{
this.x = x;
this.y = y;
}

public void Add()
{
Console.WriteLine(x + y);
}

public void Sub()
{
Console.WriteLine(x - y);
}

public void Mul()
{
Console.WriteLine(x * y);
}

public void Div()
{
Console.WriteLine(x / y);
}

static void Main()
{
Maths obj = new Maths(200, 25);
obj.Add();
obj.Sub();
obj.Mul();
obj.Div();
Console.ReadLine();
}
}

In the above program, the class requires some initialization values for the Methods to execute, which are sent to a class using Constructor only.

Static
As we are aware a class is a collection of members like variables, methods, Constructors, etc.  Basically, these members will be of two different categories.
1) Non-static (or) Instance Methods
2) Static members

The members of a class which require the object of a class for initialization or execution are called as Instance members, whereas members of a class which do not require object of a class for initialization or execution are called as static members.

Instance variables Vs Static Variables
1) A variable under a static block or a variable declared using ‘static’ modifier are called static variables, the rest of all are called instance variables only.

Eg:

int x=100;  --> instance
statc int y-100;  --> static
static void Main()
{
int z=100; --> static
}

2) The initialization of a static variable gets done if we execute the class in which the variable is declared, whereas instance variable gets initialized after creating the object of a class either within the class or in other classes.

3) The minimum and maximum number of times a static variable gets initialized will be ‘one and only one time.

Note:  To access an instance member, we use object of the class, whereas to access static members, we use name of the class.

We use Instance variables if we want any value that is specific to an object.

Constant Variables
It is a variable which contains fixed value that cannot be modified.  While declaring a constant only, we need to assign values to it.  The behavior of a constant variable will be the same as the behavior of Static variable.  The only difference is static variables can be modified, but constant variables cannot be modified.

ReadOnly Variables
These are very much similar to constants whose values cannot be modified after initialization, but their behavior will be similar to Instance variables which are initialized when the object is created and also it maintains a separate copy for each object.

A Constant value is a fixed value for the complete class, whereas ReadOnly variable is a fixed value specific for each object.

Note:  A ReadOnly variable can be initialized either in constructor or at the time of declaration.

To check all these, add a class “StatVars.cs” and write the below code.

class StatVars
{
int x = 100; //Instance
static int y = 100; //Static
public const float pi = 3.14f; //Constant
public readonly bool flag; //ReadOnly
public StatVars(bool flag)
{
this.flag = flag;
}

static void Main()
{
Console.WriteLine (StatVars.y);
Console.WriteLine (StatVars.pi);
StatVars s1 = new StatVars (true);
StatVars s2 = new StatVars (false);
Console.WriteLine (s1.x + " " + s2.x);
Console.WriteLine (s2.flag + " " + s2.flag);
Console.ReadLine ();
}
}

Static Methods Vs Instance Methods
A Method declared using static modifier is called a static method.  The rest of all are called Instance objects.  While defining static methods, make sure that we are not going to consume any non-static members of the class directly from static methods we need to consume them only using object of the class.

Note:  Non-Static members of a class cannot be consumed from static blocks of a class directly they need to be consumed using class objects.

To test this, add a class “StatMets.cs” and write the below code

class StatMets
{
int x = 100;
static int y = 200;
static void Add()
{
StatMets obj = new StatMets();
Console.WriteLine(obj.x + y);
}
static void Main()
{
StatMets.Add();
Console.ReadLine();
}
}

Static Constructor Vs Instance Constructor
A constructor declared using ‘static’ modifier is called static constructor and the rest of all are called instance constructors.

A static constructor first gets executed under a class, whereas an Instance constructor gets executed only when object of a class is created and each time the object is created.

Static constructor of a class gets executed only if we execute the class in which it was we defined, whereas Instance constructor gets executed wherever and whenever we create the object of a class in which it was defined.

Use static constructor for writing the code to perform an action when the execution of ‘class’ type, whereas use Instance Constructor to perform an action that should be executed each time the object is created.

A static constructor cannot be parameterized because we never call it directly so sending a value to it will not possible, but we can do it using parameterized Instance Constructors.

class StatCon
{
static StatCon()
{
Console.WriteLine ("Static Members");
}
StatCon ()
{
Console.WriteLine ("Instance Constructor");
}
static void Main()
{
Console.WriteLine ("Main Method");
StatCon c1 = new StatCon ();
StatCon c2 = new StatCon ();
Console.ReadLine ();
}
}

Static Classes
These are introduced in C# 2.0, which can contain only static members in it.  We cannot create object of these classes.

Happy Learning ..... !!!!


CSharp.NET Tutorial - Day 11


This post first appeared on Dot Net Programming (C#, Asp.Net, ADO.Net, WCF, WPF, Ajax, LINQ), please read the originial post: here

Share the post

CSharp.NET Tutorial – Day 10

×

Subscribe to Dot Net Programming (c#, Asp.net, Ado.net, Wcf, Wpf, Ajax, Linq)

Get updates delivered right to your inbox!

Thank you for your subscription

×