Skip to main content

C# Partial Feature:Classes and Methods

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:

public partial class Pradeep
{
public void OnLeave ()
{
}
}

public partial class Pradeep
{
public void InMeeting ()
{
}
}

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!!

Comments

Post a Comment

Popular posts from this blog

Asp.Net 4.0: An Overview-Part-III

This is the last post in the series which will explore the following new features of ASP.Net 4.0  Performance Monitoring for Individual Applications in a Single Worker Process Web.config File Refactoring Permanently Redirecting a Page Expanding the Range of Allowable URLs Performance Monitoring for Individual Applications in a Single Worker Process It is a common practice to host multiple ASP.NET applications in a single worker process, In order to increase the number of Web sites that can be hosted on a single server. This practice results in difficulties for server administrators to identify an individual application that is experiencing problems. ASP.NET 4 introduces new resource-monitoring functionality introduced by the CLR. To enable this functionality, following XML configuration snippet is added to the aspnet.config configuration file.(This file is located in the directory where the .NET Framework is installed ) <?xml version="1.0" encoding="UTF-8...

Covariance and Contravariance-General Discussion

If you have just started the exploration of .Net Framework 4.0, two terms namely Covariance and Contravariance might have been heard. The concept that these terms encapsulate are used by most developer almost daily, however there has never been any botheration about the terminologies. Now, what actually these terms mean and how are these going to affect us as a developer, if we dive in to the details. The simple answer is it’s always good to know your tools before actually using them. Enough philosophy, let’s get to the business. Starting the discussion let me reiterate that in addition to Covariance and Contravariance, there is another terminology, Invariance. I’ll by start here by diving into the details of Invariance and then proceed further. Invariance: Invariance can be better understood by considering the types in .Net.>net has basically two type, value-types and reference-types. Value types (int, double etc) are invariant i.e. the types can’t be interchanged either ...

Advanced WCF

In this post, I am sharing the link of articles about  advanced topics in WCF. The List of articles is exhaustive and can serve as your repository for all WCF queries. Concurrency,Throttling & Callbacks  WCF Concurrency (Single, Multiple and Re entrant) and Throttling   WCF-Interop and BinarySecurityToken  WCF Callbacks  Creating Web Services From WSDL Link1 Link2 Link3 Link4 WCF-Security WCF over HTTPS   Transport Security(basic)/HTTPS UserNamePasswordValidator ServerCertificateValidationCallback 9 simple steps to enable X.509 certificates on WCF - CodeProject http://www.codeproject.com/KB/WCF/9StepsWCF.aspx?display=Print Message Security(Certificate)/PeerTrust Securing WCF Services with Certificates. - CodeProject http://www.codeproject.com/KB/WCF/wcf_certificates.aspx Message Security(Certificate)/ChainTrust How To Configure WCF Security Using Only X.509 Certificates - CodePr...