Showing posts with label C# FAQ. Show all posts
Showing posts with label C# FAQ. Show all posts

Jun 27, 2008

Polymorphism, Method Hiding and Overriding in C#

Polymorphism

One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.

C# Example

Let's assume the following simple classes A and B for the discussions in this text. A is the base class, B is derived from A.


Inherited Methods

A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A {}

class Test
{
static void Main(string[] args)
{
A a = new A();
a.Foo(); // output --> "A::Foo()"

B b = new B();
b.Foo(); // output --> "A::Foo()"
}
}
}


The method Foo() can be overridden in classes B and C:

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}


There are two problems with this code.

The output is not really what we, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual.

Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'

Virtual and Overridden Methods

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

using System;
namespace Polymorphism
{
class A
{
public virtual void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public override void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "B::Foo()"
}
}
}

Method Hiding

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

using System;
namespace Polymorphism
{
class A
{
public void Foo() { Console.WriteLine("A::Foo()"); }
}

class B : A
{
public new void Foo() { Console.WriteLine("B::Foo()"); }
}

class Test
{
static void Main(string[] args)
{
A a;
B b;

a = new A();
b = new B();
a.Foo(); // output --> "A::Foo()"
b.Foo(); // output --> "B::Foo()"

a = new B();
a.Foo(); // output --> "A::Foo()"
}
}
}

Combining Method Overriding and Hiding

Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:

class A
{
public void Foo() {}
}

class B : A
{
public virtual new void Foo() {}
}


A class C can now declare a method Foo() that either overrides or hides Foo() from class B:

class C : B
{
public override void Foo() {}
// or
public new void Foo() {}
}

Important things to remember -->

1. If you are using same name in derived class it hides the base class method, and generate a compiler warning. Use new keyword to supress this warning and tells the compiler that ok i am hiding it intentional.
2. Else define the base as virtual and write override in derived class method.
3. If you dont sure whether you want to hide or override use both virtual and new in base class method definition.

Mar 20, 2008

Proxy class generation from WSDL in .NET 2.0 and .NET3.0

Proxy class generation from WSDL in .NET 2.0

The following command creates a .wsdl file for the XML Web service located at the specified URL and creates a client proxy class in the C# language for the XML Web service.

wsdl http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

The following command creates a client proxy class in the C# language for an XML Web service located at the specified URL. The tool saves the client proxy class in the file myProxyClass.cs

wsdl /out:myProxyClass.cs http://hostServer/WebserviceRoot/WebServiceName.asmx?WSDL

For more visit to:

http://msdn2.microsoft.com/en-us/library/7h3ystb6(VS.71).aspx

Proxy class generation from WSDL in .NET 3.0

Use this command to generate proxy class from a web service.

WseWsdl3 http://hostServer/WebServiceRoot/WebServiceName.asmx?WSDL /out:MyProxyClass.cs

This will generate the class MyProxyClass.cs which we can include in our solution to create an object of this and then call the appropriate method.

For more visit to :

http://msdn2.microsoft.com/en-us/library/aa529578.aspx

Mar 29, 2007

Sending Email thru C#

Sending email thru C#, .NET 2.0 , with attachment,

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;

namespace MailConnect
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Sendbutton_Click(object sender, EventArgs e)
{
MailMessage aMessage = new MailMessage("matespoint@gmail.com", "xyz@yahoo.com");
aMessage.Subject = "This is test message";
aMessage.Body = "Body text message";

Attachment aT = new Attachment("C:\files.doc");
aMessage.Attachments.Add(aT);
aT = new Attachment("C:\files.pdf");
aMessage.Attachments.Add(aT);

SmtpClient aClient = new SmtpClient(servername, 25);
aClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
aClient.Send(aMessage);
MessageLabel.Text = "Mail has been sent successfully";
}
}
}

Mar 16, 2007

Application Domain

An Application Domain is a light weight process and provides a logical and physical isolation from another .NET application.

  • This ensures that the Applications can work independent and isolated of each other. An Application Domain is created by the Common Language Runtime (CLR) and it ensures that if one Application Domain crashes or goes down, it does not in any way effect the functioning of another Application Domain.
  • Multiple .NET applications can be executed in one single process by loading these applications in separate Application Domains.
  • Several threads can be executing in a single application domain at any given time and a particular thread is not confined to a single application domain. In other words, threads are free to cross application domain boundaries and a new thread is not created for each application domain.
  • The following are the benefits of Application Domains.
    Isolation of code, data and configuration information of one application from another
    A failure in one application will not affect the other

Abstract Class Vs Interface

Abstract Class Vs Interface

There are a lot of discussion on the internet about the Interface vs Abstract class. and also , as BASE class whether we should use interface, abstract class or normal class.
Abstract Class vs Interface

We can not make instance of Abstract Class as well as Interface.
Here are few differences in Abstract class and Interface as per the definition.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are
by default public and abstract.

using System;
namespace ConsoleApplication2
{
/// /// Summary description for Class2. ///
public abstract class A
{
int someInt;
string someString;
public A()
{ // // TODO: Add constructor logic here // }
public abstract void F();
}

public class B : A
{
public override void F()
{ Console.WriteLine("F in B"); }
}

interface IA
{

//int someInt; give error we cant have fields in interface
//string someString;
string P{get;set;}
void F();
}
public class C : IA
{
public C() { }
public string P
{
get {return _p;}
set {_p = value;}
}
public void F()
{
Console.WriteLine("Abstract F()");
}
private string _p; }
}

we can make the call like this..
B b = new B();
b.F();
A a = b;
a.F();
//A a = new A(); will give error as we cant instantiate
C c = new C();
c.F();
c.P="Test String";
Console.WriteLine(c.P.ToString());
IA d = c;
d.F();
Console.WriteLine(c.P.ToString());
Console.Read();

Output :
F in B
F in B
Abstract F()
Test String
Abstract F()
Test String

We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties
allowed.
We use abstract class and Interface for the base class in our application.Now most important question: What should use : Interface force everybody to implement all things in that. So use it when u wanna force all the methods, properties, etc to implement.Abstract Class - limited you to create an instance of this class, and if you derived from this class you have to implement all abstract members to create an instance of this derived class. Also Abstract class should used when you have some functions which you must override and some which you can leave in this scenerio use abstract classes,

Mar 1, 2007

Difference between out and ref - out vs ref

In the case of Ref - assignment is needed before passing to the function
In the case of Out - no assignment is required, but you must assign a value in which function this is passed,
For Ex:
using System;
namespace ConsoleApplication2
{
///
/// Summary description for Class1.
///

class Class1 {
public static void Foo_Ref(ref int i)
{
//i = 2; //Dont gives a error
}
public static void Foo_Out(out int i)
{
//i=3; //it gives an error i must be assigned before leaving this function.
}
public static void Test()
{
int a ; Foo_Ref(ref a); //it gives an error coz a is not assigned a value
Console.WriteLine("Ref Case {0}",a);
Foo_Out(out a);
Console.WriteLine("Out Case {0}",a);
}
[STAThread] static void Main(string[] args)
{ //return MessageBoxA(0,"Hello Irfan","Caption",0);
Test();
Console.Read();
}
}
}