Dotnetfreaks' Blog | Visual Studio

Dotnetfreaks' Blog

Fabulous Adventures In DotNet

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Archive

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

C# Partial Classes and Methods


 

One of the unique features of C# is the concept of Partial, extendable to definition of a Class or a Struct, an Interface or a method.
Using this, the definition of any class, struct, interface of method can exist in two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

To split a class definition, partial keyword modifier is used.

For Example:

   1:      public partial class Pradeep
   2:      {
   3:          public void OnLeave()
   4:          {
   5:          }
   6:      }
   7:   
   8:      public partial class Pradeep
   9:      {
  10:          public void InMeeting()
  11:          {
  12:          }
  13:      }

Here, it is valid to use the same name for the class and implement desired functionality separately.
Finally, when compiled, the code is auto merged , giving a Final class named Pradeep, with the two methods that were defined separately.

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace.
Following are the points that need to be taken care of while working with Partial keyword.

  • All the parts must use the partial keyword.
  • All the parts must have the same accessibility, such as public, private, and so on.
  • All partial-type definitions meant to be parts of the same type must be defined in the same assembly and the same module (.exe or .dll file). Partial definitions cannot span multiple modules.
  • If any part is declared abstract, then the whole type is considered abstract.
  • If any part is declared sealed, then the whole type is considered sealed.
  • If any part declares a base type, then the whole type inherits that class.
  • Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations.
  • Nested types can be partial, even if the type they are nested within is not partial itself

For Example:

    class LeaveReachTimings
    {
        partial class Residence
        {
            void TimetoReach() { }
        }
        partial class Office
        {
            void TimeToLeave() { }
        }
    }


Here the Class LeaveReachTimings is not partial, but it is completely valid to declare partial classes Residence and Office as nested classes in it.

  • Attributes of partial-type definitions are merged

For Example

    [SerializableAttribute]
    partial class CurrentCompany { }

    [Obsolete Attribute]
    partial class CurrentCompany { }

    These two attributes will finally merge and are equivalent to the following.

    [SerializableAttribute]
    [Obsolete Attribute]
    partial class CurrentCompany { }

Enough of Theory Let us now create one partial Class to verify the concepts covered so far.

Partial Class:

 

    public partial class Record
    {
        private int x;
        private int y;

        public Record(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    public partial class Record
    {
        public int PrintSum()
        {
            return x + y;
        }

    }

 
Partial Methods:

Similar to Partial Classes, Partial Methods are also allowed. These are allowed in partial classes or struct.
One part of class contains the signature and the same or other part of the partial class can contain its implementation.
If no implementation is provided, then the method and all calls made to it are removed at compile time.

Therefore, any code in the partial class can use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.

A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part.

If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

Following are the considerations with Partial Methods.

  • Partial method declarations must begin with the partial keyword
  • Return Type is always void.
  • out parameters are not allowed , however ref can be used.
  • Partial methods cannot be virtual as they are implicitly private.

It means they have access modifiers such as public, private or internal. Hence, they cannot be called from outside the partial class, and cannot be declared as virtual.

  • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.
  • Partial methods can use static and unsafe modifiers.
  • Partial methods can be generic.
  • A delegate to a partial method which has an implementation, can be made. But, the partial method which has just a signature and no implementation can not have a delegate.


Example:

    public partial class PartialClassTest
    {
        private string mytest = string.Empty;

        partial void MyPartialMethodTest();

    }


    public partial class PartialClassTest
    {
        partial void MyPartialMethodTest()
        {
            mytest = "Partial Method call Succeded!!";

        }

        public string returnstring()
        {
            MyPartialMethodTest();
            return mytest;

        }
    }

Here the partial methods, always return void and to get the value of mytest string I have to declare yet another method(return string), which finally prints the string on the webpage if called as per the following code.

    protected void Page_Load(object sender, EventArgs e)
    {
        PartialClassTest ptest = new PartialClassTest();
        Response.Write(ptest.returnstring());
    }

Please note: Delegate or Enumeration declarations can not use partial keyword.

Hope this discussion was helpful.

Till Next time we connect, Happy Coding!!!




Posted by Pradeep Patel on Thursday, June 10, 2010 7:05 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Explicit Interface Implementation in C#


C# doesn't support multiple inheritances but it is been achieved using interfaces. A class in C# has the option to implement one or more interface(S). There is only one challenge when class implements multiple interfaces is that they may include methods with same name and signature as existing class members or other interfaces' members.

Explicit interface implementation gives the ability to hide the details of an interface and it is only available by casting to the interface type. Explicit interface implementation can be used to disambiguate class members and interface members otherwise they will conflict.

Lets take an example, If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

interface IInterfaceA
 
{
 
    void Paint();
 
}
 
interface IInterfaceB
 
{
 
   void Paint();
 
}
 
class SampleClassA : IInterfaceA, IInterfaceB
 
{
 
    // Both IInterfaceA.Paint and IInterfaceA.Paint call this method.
 
    public void Paint()
 
    {
 
    }
 
}
 

 

The class member IInterfaceA.Paint is only available through the IInterfaceA interface, and IInterfaceB.Paint is only available through IInterfaceB. Both method implementations are separate, and neither is available directly on the class. For example:

SampleClass obj = new SampleClass();
//obj.Paint();  // Compiler error.

IInterfaceA c = (IInterfaceA)obj;
c.Paint();  // Calls IInterfaceA.Paint on SampleClass.

IInterfaceB s = (IInterfaceB)obj;
s.Paint(); // Calls IInterfaceB.Paint on SampleClass.

 

It is possible to implement an interface member explicitly. Create a class member that is only called through the interface, and is specific to that interface. This can be achieved by naming the class member with the name of the interface and a period. For example:

public class SampleClass : IInterfaceA, IInterfaceB
 
{
 
   void IInterfaceA.Paint()
 
   {
 
        System.Console.WriteLine("IInterfaceA.Paint");
 
   }
 
   void IInterfaceB.Paint()
 
   {
 
        System.Console.WriteLine("IInterfaceB.Paint");
 
   }
 
}

 




Posted by Ajander Singh on Friday, April 02, 2010 12:04 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Interfaces in C#


An interface contains only the signatures of methods,  events, indexers or properties. When a class or struct implements the interface then that class/struct must implement the members of the interface that are specified in the interface definition.

interface IEquatable<T> 
{
     bool Equals(T obj); 
}

 

An interface cannot contain fields and members are automatically public in interface as well and an interface can inherit from one or more base interfaces. When a base type list contains a base class and interfaces, the base class must come first in the list.

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.

Interfaces can inherit other interfaces. It is possible for a class to inherit an interface multiple times, through base classes or interfaces it inherits. In this case, the class can only implement the interface one time, if it is declared as part of the new class. If the inherited interface is not declared as part of the new class, its implementation is provided by the base class that declared it. It is possible for a base class to implement interface members using virtual members; in that case, the class inheriting the interface can change the interface behavior by overriding the virtual members.

it was necessary to incorporate some other method so that the class can inherit the behavior of more than one class, avoiding the problem of name ambiguity that is found in C++. With name ambiguity, the object of a class does not know which method to call if the two base classes of that class object contain the same named method.


Interfaces Overview

An interface has the following properties:

  •       An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.
  •       An interface cannot be instantiated directly.
  •       Interfaces can contain events, indexers, methods and properties.
  •       Interfaces contain no implementation of methods.
  •       Classes and structs can inherit from more than one interface.
  •       An interface can itself inherit from multiple interfaces.



Posted by Ajander Singh on Thursday, April 01, 2010 7:04 PM
Permalink | Comments (0) | Post RSSRSS comment feed