Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Monday, October 21, 2013
Thursday, October 17, 2013
Thursday, June 7, 2012
Binding Generic List<> Class to the Gridview using DataReader or Datatable
Here now we will fetch the data of a table from Database and bind it to Gridview using ListClass.
First Create a Class
public class Buzz
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private string desc;
public string Desc
{
get { return desc; }
set { desc = value; }
}
}
public class BuzzList : List<Buzz>
{ }
In the above Class Buzz,it takes to members title and description.And also we can see another class BuzzList which is inherited from List<Buzz>
Now in the PageLoad
SqlConnection con = new SqlConnection("ur db connectionstring parameters");
SqlCommand cmd = new MySqlCommand("select * from BUZZ", con);
//BUZZ is the table in Database
con.Open();
try
{
BuzzList objBuzzList = new BuzzList();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Buzz objBuzz = new Buzz();
objBuzz.Title = dr["TITLE"].ToString();
//TITLE is the Column in BUZZ table
objBuzz.Desc = dr["DESCRIPTION"].ToString();
//DESCRIPTION is the Column in BUZZ table
objBuzzList.Add(objBuzz);
}
GridView1.DataSource = objBuzzList;
GridView1.DataBind();
}
First Create a Class
public class Buzz
{
private string title;
public string Title
{
get { return title; }
set { title = value; }
}
private string desc;
public string Desc
{
get { return desc; }
set { desc = value; }
}
}
public class BuzzList : List<Buzz>
{ }
In the above Class Buzz,it takes to members title and description.And also we can see another class BuzzList which is inherited from List<Buzz>
Now in the PageLoad
SqlConnection con = new SqlConnection("ur db connectionstring parameters");
SqlCommand cmd = new MySqlCommand("select * from BUZZ", con);
//BUZZ is the table in Database
con.Open();
try
{
BuzzList objBuzzList = new BuzzList();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Buzz objBuzz = new Buzz();
objBuzz.Title = dr["TITLE"].ToString();
//TITLE is the Column in BUZZ table
objBuzz.Desc = dr["DESCRIPTION"].ToString();
//DESCRIPTION is the Column in BUZZ table
objBuzzList.Add(objBuzz);
}
GridView1.DataSource = objBuzzList;
GridView1.DataBind();
}
Wednesday, April 11, 2012
Thursday, March 22, 2012
Friday, February 18, 2011
Why C# doesnt support Multiple inheritance
Not just C#, infact complete CLR doesn't support mutiple inheritence. However you can achieve your functionality using interfaces.
There are several reasons for multiple inheritence in not introduced in CLR.
First and foremost, .net allows you to use mutiple languages and each of these language would behave differently on how multiple inheritence works over it. So it was difficult for designers to resolve this issue.
Also mutiple inheritence create lot of complexity in the code.
for more read Why doesn't C# support multiple inheritance?
There are several reasons for multiple inheritence in not introduced in CLR.
First and foremost, .net allows you to use mutiple languages and each of these language would behave differently on how multiple inheritence works over it. So it was difficult for designers to resolve this issue.
Also mutiple inheritence create lot of complexity in the code.
for more read Why doesn't C# support multiple inheritance?
Thursday, January 27, 2011
Tuesday, December 7, 2010
STATIC in C# .NET
In C#, whenever you declare a variable which is bound to an instance (object) of a class, your variable by default gets its own copy of all the fields in the class. So for example, if you write:
CreditCardAccountPremium cp1 = new CreditCardAccountPremium();
CreditCardAccountPremium cp2 = new CreditCardAccountPremium();
cp1.setFirstName("George");
cp2.setFirstName("Harry");
-- the instances cp1 and cp2 each contain their own string called FirstName. Changing the FirstName in cp2 has no effect on the value of the FirstName in cp1. However, there are some cases where you do not want this behavior. Maybe you would like to set a maximum value for a CashAdvance that is common to the entire CreditCardAccountPremium class. This would be universally applied to all instances of CreditCardAccountPremium.
We really want the "maxCashAdvance" to be stored in memory only once, no matter how many instances of the class we instantiate. To do this, we place the keyword static before the field declaration:
public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;
....
Fields declared with the static keyword are referred to as static fields or static data., while the other fields like FirstName are called instance fields. So an instance field belongs to an object, and a static field belongs to the class as a whole. Static fields exist from the moment the assembly containing the class is loaded, and are initialized by the runtime, independent of whether you actually declare any instances of the class. Consequently, we can also have static constructors, which serve no other purpose than to assign initial values to static data:
public class CreditCardAccountSuper
{
private static uint maxCashAdvance;
staticCreditCardAccountSuper()
{
maxCashAdvance = 300;
}
If you were to invoke a CreditCardAccountSuper.maxCashAdvance property, there is no need to assign an initial value within the Main() method; the static constructor does this automatically. Note that the static constructor in which the maxCashAdvance default value is set has the same name as the class, and cannot take any arguments.
Just as is the case with fields, you can declare methods as static provided they don't try to access instance data or any other instance methods. You might want to provide a method to allow users of the class to view the maxCashAdvance value:
public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;
public static uint GetMaxCashAdvance()
{
return maxCashAdvance;
}
You access static methods and fields associated with a class differently that you access them as objects (instances of a class). Instead of specifying the name of the instance to access the method (cp1.GetMaxCashAdvance) you will specify the name of the class: CreditCardAccountPremium.GetMaxCashAdvance(). The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types. C# trashes the whole concept of global functions, variables, and constants. Instead, you can create static class members, making your C# code not only easier to read, but less likely to cause naming and other conflicts.
source:eggheadcafe
More on Static Class
http://www.c-sharpcorner.com/UploadFile/4d790c/5736/
CreditCardAccountPremium cp1 = new CreditCardAccountPremium();
CreditCardAccountPremium cp2 = new CreditCardAccountPremium();
cp1.setFirstName("George");
cp2.setFirstName("Harry");
-- the instances cp1 and cp2 each contain their own string called FirstName. Changing the FirstName in cp2 has no effect on the value of the FirstName in cp1. However, there are some cases where you do not want this behavior. Maybe you would like to set a maximum value for a CashAdvance that is common to the entire CreditCardAccountPremium class. This would be universally applied to all instances of CreditCardAccountPremium.
We really want the "maxCashAdvance" to be stored in memory only once, no matter how many instances of the class we instantiate. To do this, we place the keyword static before the field declaration:
public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;
....
Fields declared with the static keyword are referred to as static fields or static data., while the other fields like FirstName are called instance fields. So an instance field belongs to an object, and a static field belongs to the class as a whole. Static fields exist from the moment the assembly containing the class is loaded, and are initialized by the runtime, independent of whether you actually declare any instances of the class. Consequently, we can also have static constructors, which serve no other purpose than to assign initial values to static data:
public class CreditCardAccountSuper
{
private static uint maxCashAdvance;
staticCreditCardAccountSuper()
{
maxCashAdvance = 300;
}
If you were to invoke a CreditCardAccountSuper.maxCashAdvance property, there is no need to assign an initial value within the Main() method; the static constructor does this automatically. Note that the static constructor in which the maxCashAdvance default value is set has the same name as the class, and cannot take any arguments.
Just as is the case with fields, you can declare methods as static provided they don't try to access instance data or any other instance methods. You might want to provide a method to allow users of the class to view the maxCashAdvance value:
public class CreditCardAccountPremium
{
private static uint maxCashAdvance = 300;
private string FirstName;
private string LastName;
public static uint GetMaxCashAdvance()
{
return maxCashAdvance;
}
You access static methods and fields associated with a class differently that you access them as objects (instances of a class). Instead of specifying the name of the instance to access the method (cp1.GetMaxCashAdvance) you will specify the name of the class: CreditCardAccountPremium.GetMaxCashAdvance(). The static modifier can be used with fields, methods, properties, operators, and constructors, but cannot be used with indexers, destructors, or types. C# trashes the whole concept of global functions, variables, and constants. Instead, you can create static class members, making your C# code not only easier to read, but less likely to cause naming and other conflicts.
source:eggheadcafe
More on Static Class
http://www.c-sharpcorner.com/UploadFile/4d790c/5736/
Friday, October 22, 2010
Partial Classes
Partial types is a new feature in programming that is introduced in Visual Studio.Net 2005. This feature helps you to divide your types such as class, interface or any type definition across multiple files. At present, when you write any class you need to have the class in a single file, i.e., you need to start the class and end the class in the same file. In VS.Net 2005, you have the option of separating your code for the class across different files. You may split a single class across different files based on functionality, so that you have different developers work on different methods.
There is no modification done in the CLR for partial classes. The implementation of partial classes is done by the compiler for VB.Net and C# in Visual Studio .Net itself. For the CLR, whether you implement the code using partial classes or the class being in a single file, is the same. The compiler, when compiling the code in VS.Net 2005, looks for the partial classes and combines them so that the end result will look as if the code were written in a single class. After compilation the IL produced will look the same for both the implementation.
In Visual Studio .Net 2005, if you try to write some code for an event of a control, in the code-behind file now you will not see the codes that were automatically generated by VS.Net. Instead you will see the code-behind file for an .aspx page which will be a partial class for that page. Since, a class file can be slit across different files, the automatic code generated are placed in a different file which will have a partial class for that .aspx page. Thus, you will see very little code in the code-behind file.
Partial classes are declared using the "partial" keyword. Let us look at the sample code that is given below in C#, which implements a class as partial classes in different files.
Example
//FirstFile.cs
using System;
interface IPartialClass
{
void PrintAString(string s);
void PrintAString();
}
partial class MyPartialClass
{
private string s = "Variable from a separate Partial Class.";
}
class MainClass
{
static void Main(string[] args)
{
MyPartialClass PClass = new MyPartialClass();
PClass.PrintAString("String from a Partial Class.");
PClass.PrintAString();
Console.ReadLine();
}
}
//SecondFile.cs
using System;
public partial class MyPartialClass : IPartialClass
{
public void PrintAString(string str)
{
Console.WriteLine(str);
}
}
//ThirdFile.cs
using System;
partial class MyPartialClass
{
public void PrintAString()
{
Console.WriteLine(s);
}
}
The code given above has three different files, FirstFile.cs, SecondFile.cs, and ThirdFile.cs. The first file has an interface IPartialClass declared in it. This interface is implemented in two other files, SecondFile.cs and ThirdFile.cs. You may note that the method PrintAString(string str) is implemented in the SecondFile.cs and the method PrintAString() is implemented in the ThirdFile.cs. You may note that the string variable 's' is declared in the FirstFile.cs. The IL produced after compiling this code in VS.Net 2005 will look the same as if compiled in earlier versions of VS.Net 2005 and the CLR finds no difference in the IL produced.
If you are not implementing all of the methods in the interface in the partial classes, you will get a compilation error stating that you have not implemented all of the methods. This is the same type of error that you get if you have a single class in a single file.
The PrintAString method in the above example is an overloaded method. A unique overloaded method is implemented in the SecondFile.cs and the ThirdFile.cs respectively. If the signature for the overloaded method in different files does not differ, you will get an error stating that the signature are the same, which is again the same type of error that you get when you have a single class instead of partial classes.
The intelligence in Visual Studio .Net 2005 recognizes the partial class and the implementation of the interfaces across different files. You may note that the private string variable declared in the FirstFile, has the scope in the ThirdFile.cs in which that string variable is actually used.
This type of splitting the class across different files, help in increasing the productivity, as a single big class running into thousands of lines of code can be split into different files. Each of these file can have a different functionality to be developed, which can be given to different developers.
There is no modification done in the CLR for partial classes. The implementation of partial classes is done by the compiler for VB.Net and C# in Visual Studio .Net itself. For the CLR, whether you implement the code using partial classes or the class being in a single file, is the same. The compiler, when compiling the code in VS.Net 2005, looks for the partial classes and combines them so that the end result will look as if the code were written in a single class. After compilation the IL produced will look the same for both the implementation.
In Visual Studio .Net 2005, if you try to write some code for an event of a control, in the code-behind file now you will not see the codes that were automatically generated by VS.Net. Instead you will see the code-behind file for an .aspx page which will be a partial class for that page. Since, a class file can be slit across different files, the automatic code generated are placed in a different file which will have a partial class for that .aspx page. Thus, you will see very little code in the code-behind file.
Partial classes are declared using the "partial" keyword. Let us look at the sample code that is given below in C#, which implements a class as partial classes in different files.
Example
//FirstFile.cs
using System;
interface IPartialClass
{
void PrintAString(string s);
void PrintAString();
}
partial class MyPartialClass
{
private string s = "Variable from a separate Partial Class.";
}
class MainClass
{
static void Main(string[] args)
{
MyPartialClass PClass = new MyPartialClass();
PClass.PrintAString("String from a Partial Class.");
PClass.PrintAString();
Console.ReadLine();
}
}
//SecondFile.cs
using System;
public partial class MyPartialClass : IPartialClass
{
public void PrintAString(string str)
{
Console.WriteLine(str);
}
}
//ThirdFile.cs
using System;
partial class MyPartialClass
{
public void PrintAString()
{
Console.WriteLine(s);
}
}
The code given above has three different files, FirstFile.cs, SecondFile.cs, and ThirdFile.cs. The first file has an interface IPartialClass declared in it. This interface is implemented in two other files, SecondFile.cs and ThirdFile.cs. You may note that the method PrintAString(string str) is implemented in the SecondFile.cs and the method PrintAString() is implemented in the ThirdFile.cs. You may note that the string variable 's' is declared in the FirstFile.cs. The IL produced after compiling this code in VS.Net 2005 will look the same as if compiled in earlier versions of VS.Net 2005 and the CLR finds no difference in the IL produced.
If you are not implementing all of the methods in the interface in the partial classes, you will get a compilation error stating that you have not implemented all of the methods. This is the same type of error that you get if you have a single class in a single file.
The PrintAString method in the above example is an overloaded method. A unique overloaded method is implemented in the SecondFile.cs and the ThirdFile.cs respectively. If the signature for the overloaded method in different files does not differ, you will get an error stating that the signature are the same, which is again the same type of error that you get when you have a single class instead of partial classes.
The intelligence in Visual Studio .Net 2005 recognizes the partial class and the implementation of the interfaces across different files. You may note that the private string variable declared in the FirstFile, has the scope in the ThirdFile.cs in which that string variable is actually used.
This type of splitting the class across different files, help in increasing the productivity, as a single big class running into thousands of lines of code can be split into different files. Each of these file can have a different functionality to be developed, which can be given to different developers.
Tuesday, June 15, 2010
Generics in C#
Introduction
Some New features have been added to C# language with version 2.0 of .NET. which are:
Generics
Iterators
Anonymous methods
Partial classes
In this Article I will explain about Generics Feature with some examples.
Generics
Generics are used to help make the code in the software components much more reusable. They are a type of data structure that contains code that remains the same. The data type of the parameters can change with each use.The usage within the data structure adapts to the different data type of the passed variables.
Each time the generic is used, it can be customized for different data types without needing to rewrite any of the internal code. Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate.
We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. An example where we could implement Generics is in dealing with collections of items (integers, strings, Orders etc.). We can create a generic collection than can handle any Type in a generic and Type-Safe manner. For example, we can have a single array class to store a list of Users or even a list of Items, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Items, and not as objects (with boxing/unboxing, casting).
Generics Implementation
Let us explore an example to understand the need for Generics and the Implementation part of it. Normally we write the Arraylistclass as:
class MyArrayList
{
private object[] items;
private int count=0;
...
public void Add(object item)
{
items[count++] = item;
}
public object GetItem(int index)
{
return items[index];
}
}
In this code, any untyped object can be added to the list and be read. While adding an untyped object is possible in a direct manner , there has to be an explicit type conversion on a read access. The untyped declaration of the list results in two problems.
The compiler has no chance to verify the content of the list and the necessary type conversions.
Type failures will be recognized only at runtime-or maybe never recognized at all.
You can solve both problems by using typed classes. The base class library provides an abstract base class, CollectionBase in the System.Collections namespace, that will enable you to create typed collections easily. You have to implement the body for the different methods and the indexer. Internally, the objects are stored in an untyped ArrayList, and calls are forwarded to this class. For reference types, this approach works very well, although a new class has to be explicitly developed for each data type. However, collections for value types created in this way are inefficient, because the data needs to be (un)boxed to be stored in the ArrayList internally. The solution for problems like this is the use of generic classes. A blueprint of the class is created just once. Instead of using a particular data type or object, a specific placeholder is added.
// Defining a Generic Class
class MyArrayList
{
private ItemType[] items;
private int count;
...
public void Add(ItemType item)
{
items[count] = item;
}
public ItemType GetItem(int index)
{
return items[index];
}
The class MyArrayList can be specialized for any data-type which would, later in the class, be referenced using the name ItemType class MyArrayList
We replaced the data type of items with ItemType.
Now we can utilize MyArrayList for various types.
For example, the code
MyArrayList iList = new MyArrayList();
Will create an instance of MyArrayList class that accepts and return only integers or that has replaced ItemType in class definition with int. Now we can only add and retrieve integers from iList.
static void Main()
{
MyArrayList iList = new MyArrayList();
iList.Add(25);
int iValue2 = iList.GetItem(1);
}
Similarly for user defined type 'Employee'
static void Main()
{
MyArrayList pList = new MyArrayList();
pList.Add(new Employee("John"));
}
Using Multiple Types
We can define more than one type in Generic Definition. A practical example is a dictionary that can be typed individually on both the key and the value.
In this case, it allows multiple placeholders. They have to be specified in angle brackets, separated by commas.
public class MyDictionary
{
public void Add(KeyType key, ValueType value)
{
// ...
}
public ValueType this[KeyType key]
{
get { return ValueType.default; }
}
}
Although using Generics is type safe, you don't have type-safe access while developing the class itself. Because the type with which the generic class is used later is absolutely unknown, it's internally assumed to be object. Specific members of the data type can only be accessed after an explicit and therefore unsafe conversion. Possible failures will only be detected at run time.
Using Methods
Methods are another exciting field of use for Generics. Generic methods will allow you to pass one or more data types. An Example is given below.
public class MyClass
{
protected ItemType MyMethod(ItemType item)
{
return item;
}
}
Conclusion
Generics are very important and useful if you work, for example, with any kind of collections. Because of the backwards compatibility of ASP.NET 2.0, the existing collections couldn't be modified. Instead, a new namespace named System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following:
Dictionary
List
Queue
SortedDictionary
Stack
In the case of C#, generics are declared and type checked at compile time while instantiated at runtime just like any other object. C#Generics has the following advantages:
The Program becomes statically typed, so errors are discovered at compile-time.
No runtime casts are required and the program runs faster.
Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
Reference : ASP.NET 2.0 Revealed, by Patrick Lorenz.
Some New features have been added to C# language with version 2.0 of .NET. which are:
Generics
Iterators
Anonymous methods
Partial classes
In this Article I will explain about Generics Feature with some examples.
Generics
Generics are used to help make the code in the software components much more reusable. They are a type of data structure that contains code that remains the same. The data type of the parameters can change with each use.The usage within the data structure adapts to the different data type of the passed variables.
Each time the generic is used, it can be customized for different data types without needing to rewrite any of the internal code. Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate.
We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. An example where we could implement Generics is in dealing with collections of items (integers, strings, Orders etc.). We can create a generic collection than can handle any Type in a generic and Type-Safe manner. For example, we can have a single array class to store a list of Users or even a list of Items, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Items, and not as objects (with boxing/unboxing, casting).
Generics Implementation
Let us explore an example to understand the need for Generics and the Implementation part of it. Normally we write the Arraylistclass as:
class MyArrayList
{
private object[] items;
private int count=0;
...
public void Add(object item)
{
items[count++] = item;
}
public object GetItem(int index)
{
return items[index];
}
}
In this code, any untyped object can be added to the list and be read. While adding an untyped object is possible in a direct manner , there has to be an explicit type conversion on a read access. The untyped declaration of the list results in two problems.
The compiler has no chance to verify the content of the list and the necessary type conversions.
Type failures will be recognized only at runtime-or maybe never recognized at all.
You can solve both problems by using typed classes. The base class library provides an abstract base class, CollectionBase in the System.Collections namespace, that will enable you to create typed collections easily. You have to implement the body for the different methods and the indexer. Internally, the objects are stored in an untyped ArrayList, and calls are forwarded to this class. For reference types, this approach works very well, although a new class has to be explicitly developed for each data type. However, collections for value types created in this way are inefficient, because the data needs to be (un)boxed to be stored in the ArrayList internally. The solution for problems like this is the use of generic classes. A blueprint of the class is created just once. Instead of using a particular data type or object, a specific placeholder is added.
// Defining a Generic Class
class MyArrayList
{
private ItemType[] items;
private int count;
...
public void Add(ItemType item)
{
items[count] = item;
}
public ItemType GetItem(int index)
{
return items[index];
}
The class MyArrayList can be specialized for any data-type which would, later in the class, be referenced using the name ItemType class MyArrayList
We replaced the data type of items with ItemType.
Now we can utilize MyArrayList for various types.
For example, the code
MyArrayList iList = new MyArrayList();
Will create an instance of MyArrayList class that accepts and return only integers or that has replaced ItemType in class definition with int. Now we can only add and retrieve integers from iList.
static void Main()
{
MyArrayList iList = new MyArrayList();
iList.Add(25);
int iValue2 = iList.GetItem(1);
}
Similarly for user defined type 'Employee'
static void Main()
{
MyArrayList pList = new MyArrayList();
pList.Add(new Employee("John"));
}
Using Multiple Types
We can define more than one type in Generic Definition. A practical example is a dictionary that can be typed individually on both the key and the value.
In this case, it allows multiple placeholders. They have to be specified in angle brackets, separated by commas.
public class MyDictionary
{
public void Add(KeyType key, ValueType value)
{
// ...
}
public ValueType this[KeyType key]
{
get { return ValueType.default; }
}
}
Although using Generics is type safe, you don't have type-safe access while developing the class itself. Because the type with which the generic class is used later is absolutely unknown, it's internally assumed to be object. Specific members of the data type can only be accessed after an explicit and therefore unsafe conversion. Possible failures will only be detected at run time.
Using Methods
Methods are another exciting field of use for Generics. Generic methods will allow you to pass one or more data types. An Example is given below.
public class MyClass
{
protected ItemType MyMethod(ItemType item)
{
return item;
}
}
Conclusion
Generics are very important and useful if you work, for example, with any kind of collections. Because of the backwards compatibility of ASP.NET 2.0, the existing collections couldn't be modified. Instead, a new namespace named System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following:
Dictionary
List
Queue
SortedDictionary
Stack
In the case of C#, generics are declared and type checked at compile time while instantiated at runtime just like any other object. C#Generics has the following advantages:
The Program becomes statically typed, so errors are discovered at compile-time.
No runtime casts are required and the program runs faster.
Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
Reference : ASP.NET 2.0 Revealed, by Patrick Lorenz.
Wednesday, December 23, 2009
Necessity for Object Oriented Programming Language.
In simple terms, why we have moved from C(Procedural Language) to C++(Object Oriented Language) ?
In C we use user defined data types like Structure, Union etc, where as in C++ we use classes, here I will try to answer the above question in terms of using these different language elements:
1. The variables we use in a structure or union can be accessed any where in the program, this means, that there is no proper security for data in C i.e. Procedural Langauage. Where as in c++ we have access specifiers like public, private, protected etc, which allows us to restrict the access to a particular variable. So unlike C, C++ has some control over the access to the data.
2. The variables/ elements of one structure are cannot be accessed in an other structure unless they are nested, so there is some access limitations for data in C. Where as in C++ the variables declared and used in one class are allowed/ restricted to get accessed by other classes throught the same access specifiers public, private, protected etc.
3. Function concepts is not supported by structures in C i.e, we cant declare a function as a structure member, where classes can have functions as their members.
These are a few reasons, where there is a necessity to move from a structure oriented language to a object oriented language.
Monday, December 21, 2009
Interfaces
* Interface is the collection of all public members of the class.
* Interface,like classes,defines a set of properties,methods and events.But unlike classes ,interfaces do not provide implementation.
* This is a powerful programming tool because they allow you to separate the definition of objects from their implementation.
* All the members of the interface are by default public and abstract.we need not specify.
* An interface body is limited to declaration for methods,property,indexer.
* Fields,constructor,constants etc cannot be included in an interface.
* Interface members are implicitly public and it is a compiler error to specify the access level explicitly.
* No implementations are allowed in an interface.
* Methods are specified by giving only the return type,name and parameters list followed by a semicolon.
Syntax with example:
interface IFigure
{
int Dimension
{set;get}
double Area();
double Perimeter();
}
Where do we use interface:
* Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
Interfaces are more flexible than base classes because you can define a single implementation multiple interfaces.
using System;
namespace InterfaceTest1
{
interface CA{
void Foo(); }
interface CB{
void Foo(); }
public class CC:CA,CB
{
//CA members
public void Foo(){
Console.WriteLine("From CA");
}
//CB members
void CB.Foo(){
Console.WriteLine("From CB");
}
}
class Class1
{
[STAThread]
static void Main(string[]args)
{ CC c = new CC();
CA ca; //Interface variable
CB cb; //Interface variable
ca=c; // Explicit implementation
ca.Foo();
cb=c; // Explicit implementation
cb.Foo();
}}}
The output is CA
CB
* Interfaces are better in situations in which you do not need to inherit implementation from a base class.
* Interfaces are useful in cases where you cannot use class inheritance.For example ,structures cannot inherit from classes,
but they can implement interfaces.
An interface represents a contract, in that a class that implements an interace must implement every aspect of that interface exactly as it is defined.
Example:
using System;
namespace InterfaceTEST
{
interface IFigure //INTERFACE
{
int Dimension
set;get}
double Area();
double Perimeter();
}
class Circle:IFigure //CLASS
{
private int mRadius;
public int Dimension{
get{return mRadius;}
set { mradius = value;}}
public double Area(){
return Math.PI*Dimension*Dimension;
}
public double Perimeter(){
return 2* Math.PI*mradius;
}
}
class Square :IFigure //CLASS
{
private int mSide;
public int Dimension{
get{return mside;}
set { mside = value;}}
public double Area()
{return mside * mside;}
public double Perimeter()
{return 4*mside;}
}
class Class1
{
[STAThread]
static void Main(string[]args)
{ //Circle
Circle C = new Circle();
C.Dimension = 10;
Console.WriteLine("Area of circle=" + C.Area());
Console.WriteLine("Perimeter of circle=" + C.Perimeter());
//Square
Square S = new Square();
S.Dimension =5;
Console.WriteLine("Area of square=" + S.Area());
Console.WriteLine("Perimeter of square=" + S.Perimeter());
}
}
}
* Interface,like classes,defines a set of properties,methods and events.But unlike classes ,interfaces do not provide implementation.
* This is a powerful programming tool because they allow you to separate the definition of objects from their implementation.
* All the members of the interface are by default public and abstract.we need not specify.
* An interface body is limited to declaration for methods,property,indexer.
* Fields,constructor,constants etc cannot be included in an interface.
* Interface members are implicitly public and it is a compiler error to specify the access level explicitly.
* No implementations are allowed in an interface.
* Methods are specified by giving only the return type,name and parameters list followed by a semicolon.
Syntax with example:
interface IFigure
{
int Dimension
{set;get}
double Area();
double Perimeter();
}
Where do we use interface:
* Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.
Interfaces are more flexible than base classes because you can define a single implementation multiple interfaces.
using System;
namespace InterfaceTest1
{
interface CA{
void Foo(); }
interface CB{
void Foo(); }
public class CC:CA,CB
{
//CA members
public void Foo(){
Console.WriteLine("From CA");
}
//CB members
void CB.Foo(){
Console.WriteLine("From CB");
}
}
class Class1
{
[STAThread]
static void Main(string[]args)
{ CC c = new CC();
CA ca; //Interface variable
CB cb; //Interface variable
ca=c; // Explicit implementation
ca.Foo();
cb=c; // Explicit implementation
cb.Foo();
}}}
The output is CA
CB
* Interfaces are better in situations in which you do not need to inherit implementation from a base class.
* Interfaces are useful in cases where you cannot use class inheritance.For example ,structures cannot inherit from classes,
but they can implement interfaces.
An interface represents a contract, in that a class that implements an interace must implement every aspect of that interface exactly as it is defined.
Example:
using System;
namespace InterfaceTEST
{
interface IFigure //INTERFACE
{
int Dimension
set;get}
double Area();
double Perimeter();
}
class Circle:IFigure //CLASS
{
private int mRadius;
public int Dimension{
get{return mRadius;}
set { mradius = value;}}
public double Area(){
return Math.PI*Dimension*Dimension;
}
public double Perimeter(){
return 2* Math.PI*mradius;
}
}
class Square :IFigure //CLASS
{
private int mSide;
public int Dimension{
get{return mside;}
set { mside = value;}}
public double Area()
{return mside * mside;}
public double Perimeter()
{return 4*mside;}
}
class Class1
{
[STAThread]
static void Main(string[]args)
{ //Circle
Circle C = new Circle();
C.Dimension = 10;
Console.WriteLine("Area of circle=" + C.Area());
Console.WriteLine("Perimeter of circle=" + C.Perimeter());
//Square
Square S = new Square();
S.Dimension =5;
Console.WriteLine("Area of square=" + S.Area());
Console.WriteLine("Perimeter of square=" + S.Perimeter());
}
}
}
Inheritance
Inheritance is a process to create new class from an exiting class.
Or
Inheritance is the process that allows the reuse of an exiting class to build a new class.
Mainly,Inheritance is based on the principal of code reuse.Instead of creating a class from scratch,it is possible to add new methods,properties and events (events are responce to user actions.)to exiting classes,thus saving time and efforts.The class on which the new class is created is called Base class or Parent class and the class that is created is called Derived, Sub or Child class.
Example:
using System;
namespace InheritanceDemo1
{
//Base class
public class Person
{
private string_name;
private int_age;
public void GetInfo()
{
Console.WriteLine("Enter your name = ");
_name = Console.ReadLine();
Console.WriteLine("Enter your age = ");
_age = int.Parse(Console.ReadLine());
}
public void DispInfo()
{
Console.WriteLine("Dear {0},Your age is {1}",_name,_age) ;
}
}
//Derived class
public class Student:Person
{
private string_school;
private int_english;
private int_math;
private int_science;
public void GetMarks()
{
Console.WriteLine("Enter school names = ");
_school = Console.ReadLine();
Console.WriteLine("Enter marks for English,Maths,Science");
_english = int.Parse(Console.ReadLine());
_math = int.Parse(Console.ReadLine());
_science = int.Parse(Console.ReadLine());
Console.WriteLine("Total Marks obtained : {0}",_english+_math+_science);
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Student objstudent = new Student();
objstudent.GetInfo(); //Accessing base member
objstudent.DispInfo(); //Accessing base member
objstudent.GetMarks();
}
}
}
Base Keyword
The keyword base is used to access members of the base class from inside a derived class.To call a method of the base class is possible even if it has been overridden in the derived class by using the keyword base.Also,creating an instance of a derived class
The constructor of the base classes can be called using base keyword
Constructor, an instance method of an instance property accessory only of the base class can be accessed using the keyword base.
Example:
using System;
namespace InheritanceDemo1
{
public class CA
{
private int priA;
public CA()
{ priA =100;
}
protected void fun(){
Console.WriteLine("From CA"); }
}
public class CB:CA {
private int priB;
public CB(){
priB = 200; }
public void foo(){
base.fun();
Console.WriteLine("From CB");
}
public class UsingBaseKeyword
{
statci void Main(string[] args) {
CB b = new CB();
b.foo(); }}}
* Calling base class constructor by using derived class using base keyword.
Example:
using System;
namespace InheritanceDemo1
{
//Base class
public class Person
{
private string_name;
private int_age;
//base supplies constructor to perform initialization
public Person(string name,int age)
{
this._name = name;
this._age = age;
Console.WriteLine("Name = {0} ",name);
Console.WriteLine("Age = {0} ",age);
}
}
//Derived class
public class Student:Person
{
private int _id;
public Student(String name,int age,int id):base (name,age)
{
this._id=id;
Console.WriteLine("Id = {0} ",id);
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
Student objstudent = new Student("Raj",24,4);
}
}
}
Method Overriding in C#
Overriding :- Overriding a method of base class means changing its implementation or overwriting it in the derived class.
*Override keyword:
The override keyword is used to modify a method.An override method provides a new implementation of the base method.For this the base class method has to be declared virtual.Adding virtual to a base class method marks it to for overriding its implementation in the derived class.By default, methods are non-virtual in C# and hence they cannot be overridden.
Note:-
1. The overridden method in a derived class should have the same signature as the base class method it is overriding.
2. The keywords new,static,virtual cannot be used along wirg the override modifier.
*Virtual keyword :
C# provides a keyword virtual that is used the definition of a method to support polymorphism.The virtual keyword is used to modify a method declaration in a class.Such method is called a virtual method.The child classes are now free to implement their own versions of thr virtual method
using override keyword.
The Syntax:-
[Access modifier]virtual[return tyoe]name([parameter list])
{
//Virtual method implementation.
}
Note: The virtual modifier cannot be used with modifier like static and override.
Ex:-
Public virual void function_name()
{
Console.WriteLine("This is a virtual method and can be overridden");
}
* When a virtual method is called ,a runtime check is made to identify the object and the appropriate method is invoked.In case of non-virtual methods,this information is available at compile time,so no runtime check to identify the object is done.
* "new" keyword:- The new keywordmis used as an operator or as a modifier,This section is discussingthe new modifier.The new modifier is used to explicitly hide a member that is inherited from the base class.This means in case if the derived class has a member with the same name as a member in the parent class,then new distinguishes the derived class member as a completely new member.
* Note:- It is an error to use both new an override on the same method.
* Note:- To conclude ,the real benefit of "new modifier" is to be sure that the intention is to hide the base method and this did not happen by accident or misspelling
* Conversely,if a method is declared as new and it does not really hide a base method ,the compiler will also issue a warning that can be suppressed by removing the new modifier.
Friday, October 9, 2009
Subscribe to:
Posts (Atom)