Named and Optional parameters in C#

Named and optional parameters were two new features added in C# 4.0. Especially optional parameters have provided an alternative to creating overloaded functions to achieve a requirements. Using these two concepts is very easy. So let’s discuss them one by one.

Optional Parameters :

The basic concept of using optional parameters is to simply define extra parameters in an existing function definition, with some default values. Setting default values to the parameters, allows us to omit the need of passing any value for these new added parameters while making the function call. If no value is specified for these parameters, while calling these functions, it will use the default values which we declared in the function definition.

For ex, we have a simple function to calculate the sum of two numbers a and b. We create the instance of the class and use the sum function.

Named and Optional parameters in C#

Now we would like to add another variable, say c, into the sum. But we need to use the same function and add the value of c, only if it is greater then 0. To do so, we will add the c parameter with a default value of 0, in the function definition. When we call the function, we will have two options to call this function. We can either keep calling the function, like we did above, or we can pass a value for the variable c.

When we call the function like we did above, without passing any value for c, it will always use the default value of 0 for c and use it in calculations. So results are not affected.

In second case, we can pass some value for the c, greater then 0, and it will be used in our calculations, to generate the result. So our code changes to :

Named and Optional parameters in C#

This could have been done using function overloading as well, with new version of the same function. If you provide the parameter, then it calls the overloaded function or else it calls the old version of the function. The only thing here is that you need not create any overloaded version of the function and simply declare a parameter as optional. Based on its value received, you can add if conditions in your function and get the job done.

This is just a small example to use of these parameter types. Real world requirements can be more complex and we can have values of type Boolean, string or even instance of any List or class type to pass as an optional parameters.

Named Parameters :

This concept of passing parameters allows the user to explicitly specify the names of the variables, along with their values, when the function is being called. For ex, in the same example we discussed above, we can use the concept of named parameters like the following :

Named and Optional Parameters in C#

So simple to use these parameters. No need to worry about the order of the parameters now, as we have added the name along with the values.

But the actual advantage of named parameters comes into picture, when we use multiple optional parameters. Suppose we have 2 or more optional parameters defined in the above function, say c and d. Now when we call the function, we may either need to pass the value of c or value of d, only one at a time. So our code changes to

Named and Optional parameters in C#

But our function is having 2 variables as optional and we will be passing only one of them at a given point of time, then how it will be possible to identify which value is for c and which is for d. So this is where we can use the named parameters and explicitly specify, which parameter we are sending and which is to be used with a default value. So in our case, we will be sending a value for the variable d and using the default value of c for calculations.  So we have the code as :

Named and Optional Parameters in C#
We can see here that d is having the value that we had set in the calling function i.e. 30 and c is using the default value of 40.

So this was about the concept of Named and Optional parameters. Hope you enjoyed reading it.

Pass data from user control to parent page using events and delegates

Using web user controls is quite a common approach in developing web applications. While using them, we often get into a situation, where we need to pass some kind of data from the user control to the parent page, when any operation is performed on the user control. For ex, we may need to pass data, on OnClick event of a button on the user-control, to the parent page. In order to achieve such a functionality, delegates are one of the most helpful ways of doing this. So let’s create a sample application to discuss this approach.

Our example will consist of a Default.aspx page and ChildControl.ascx user-control. This user-control will have a button with OnClick event attached to it. On click of this button, we will send current datetime to the parent page. So for initial setup, add a button on the user-control and place the user-control on page.

To achieve this, our logic has to be, to notify the parent page that some action has been performed on the user-control. For this, our page must subscribe or attach itself to the user-control, using some kind of mechanism. This mechanism which will be the events in our case. This is similar to the concept of subscribing to newsletters or event notifications on any website. When any newsletter is published or some event happens on a website, you get an email notification of it. Similar is the case here. Whenever the event (to which parent page has subscribed) is fired, subscriber will receive notifications. So let’s start the code step wise.

Step 1 : Create a delegate on the user-control, that can encapsulate a method which takes no input and returns DateTime type. Also, declare an event on the user control, which is of the delegate type which we created.

Pass data from user control to parent page using events and delegates

Step 2 : Our main page will subscribe to the event that we created on the user-control, to get notification of when the event is fired on the user control.

Pass data from user control to parent page using events and delegates

Step 3 : Next, when the button click functionality is done, we explicitly execute the event by calling the GetDataFromChild event, passing the required data.

Pass data from user control to parent page using events and delegates

Step 4 : Run the application and click the button. On clicking of button, when we make the explicit call to the event from the user control, parent page receives the notification through the ucChild_GetDataFromChild method.

Pass data from user control to parent page using events and delegates

How it works ?

Now that we have successfully created the sample application, let’s discuss how this process is actually working. To start with, we have used the combination of event and delegates. We create a delegate of type ChildControlDelegate and an event of the same type, on the user-control. Our parent page attaches itself, to this event. Whenever the user-control finishes its task on button click, it executes the event by calling GetDataFromChild and the main page receives the notification in a method named ucChild_GetDataFromChild.

Like we discussed an example at the start of the article, when we subscribe for any newsletter on any website, we get the notification emails of it. Same is the case here.

Important point to note here is that when we attached the event on the parent page (using += syntax), it is like we are actually adding a method, which this event will execute when it is fired. This method is added with the help of a delegate. It basically acts as a receiver for the parent page. So whenever we explicitly call the event from the user-control, using the  GetDataFromChild(DateTime.Now) statement, Default page will invoke the receiver method on it (which in this case is ucChild_GetDataFromChild ) to get receive the results from the user control.

So this was how we can pass data from user-control to parent page. Hope you enjoyed reading it…!!!

var vs dynamic keywords in C#

Programming languages can be normally considered to be either statically typed or dynamically typed. A static (Not to be mixed with static keyword, used for classes) typed language validates the syntax or checks for any error during the compilation of the code. On the other hand, dynamically typed languages validate the syntax or checks for any error, only at the run time. For ex, C# & JAVA are a static type and javascript is dynamic type language.

C# was earlier considered as a statically typed language, as all the code written was validated at the compile time itself. But, with the introduction of the dynamic keyword in C# 4.0, it became a dynamic typed language also. The two concepts of static and dynamic types in C# can be illustrated with the use of two keywords named var and dynamic.  Let’s discuss about some basic differences between these two, based on some of their characteristics.

1. When were they introduced :

  • var was introduced in C# 3.0
  • dynamic was introduced in C# 4.0

2. Type inference of variables :

  • var is a statically type variable. It results in a strongly typed variable i.e. the data type of these variables are inferred at compile time. This is done based on the type of value, with which these variables are initialized.
  • dynamic are dynamically typed variables. This means, their type is inferred at run-time and not the compile time in contrast to var type.

3. Initialization of variables :

  • var type of variables are required to be initialized at the time of declaration or else they run in compile time error as : Implicitly-typed local variables must be initialized.
  • dynamic type variables need not be initialized, when declared.

4. Changing type of value assigned:

  • var does not allows to change the type of value assigned, which is once assigned to it. This means, if we assign an integer value to a var, we cannot assign string value to it. This is because, on assigning the integer value, it will be treated as of integer type thereafter. So further any other type of value cannot be assigned. For ex, following code will give a compile time error

var vs dynamic in C#

  • dynamic allows to change the type of value, assigned to it initially. In the above code, if we use dynamic instead of var, it will not only compile, but will also work at run-time. This is because, at run time, the value to the variable is first inferred as Int32 and when its value is changed, it is inferred as string type.

var vs dynamic in C#

5. Intellisense help :

  • Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, compiler has all the information related the type. So we have the intellisense help available. See the code below. We have a var variable initialized with a string value. So its type is known to the compiler and we have the appropriate intellisense help available for it.

var vs dynamic in C#

  • Intellisense help is not available for dynamic type of variables as their type is unknown till run time. So intellisense help is not available. Even you will be informed by compiler as - This operation will be resolved at run-time. See the code below :

var vs dynamic in C#

6. Restrictions on the usage :

  • dynamic variables can be used to create properties and return values from a function.
  • var variables cannot be used for property or return value from a function. They can be only used as local variables in a function.

var vs dynamic vs object ?

If we closely observe dynamic type, it is performing pretty much the same task which the object type (which is the base type of all other types) does. Then what is the difference between object type and var then ? Also, why we need var when we have the object type. Let’s discuss these points by doing some comparisons.

  1. While using object type, compiler provides only generic information, functionality or functions related to the type it holds, until it is being type cast into its actual type. This means, even if we have stored any integer or string values in an object type, we will get their related functions, only if we convert the object type into its actual type. See the code below :

var vs dynamic in C#
Here, we only have generic properties and functions available for the type of value stored in it, which we will have, even if we store any integer or other type of value in it. Now, let’s convert it to its actual type i.e. string.

var vs dynamic in C#

Now after explicit conversion, we have the properties & functions specific to the string type. In case we use the var type to store the same value, we would not be required to do the explicit conversion, as compiler already infers its type from the value initialized and we will have its functions and properties.

2.  Based on the above point, object types increase the overhead of boxing and un-boxing, before we can use the actual values stored in it or use any function related to it. But this is not the case with var, as we already know its type at the time of use. For ex, in above code, we get to use the functions related to string only after we convert the object into string. So this results in un-boxing. On the other hand, for dynamic types, we only need to know that the function or property we are using, actually exists for the type of value being stored in it.

var vs dynamic in C#

For example, in above code, if we know that dynamic variable will be storing string type, then we can use Length type property, even if it is not available in the intellisense help.

3. Next, we need to be careful while casting or converting the values, when using the dynamic or object type variables. Any wrong casting can result in run time errors. On the other hand, var type will give a compile time error with wrong conversion. So any run time error is not possible.

var vs dynamic in C#

Here, object type stored string value, but we are trying to cast into integer type. So will throw run time error.

var vs dynamic in C#

Similarly, we are storing back the string value, into integer type. So it would again result in error.

4.  In terms of interoperability with different frameworks, earlier we required object type to be used to get the underlying object type and then use reflection to access the related methods or functions. But with the introduction of dynamic keyword, we only need to know that a function or property exists on the underlying object and rest we simply need to make a call to these properties or functions.

5. As per MSDN,  “…..As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time….”.

From these points, we cannot conclude which specific type we should use. It all depends on requirements whether we should go for var or dynamic or object type.

So this was all about the basic differences between var and dynamic keywords. Hope you enjoyed reading it…!!!

Message Contract in WCF

Few years back, when WCF was introduced, i was very eager to learn about this technology. I got few chances to work on it and i came across the concept of FaultContract and MessageContract. But was not able to dig deep into these concepts. Finally, I decided to spend some time to these concepts of MessageContracts as well.

What is Message Contract

While using wcf service, in order to send the data, like any custom class data, developers don’t have to do anything except adding the DataContract & DataMember attributes on the type of data, which is to be transferred. Developer need not to be concerned about serializing the data, converting it into SOAP xml and sending to the client. To check this, let’s create a sample application.

Add a new WCF application and add 2 classes named RequestData and ResponseData. RequestData is having a property named EmployeeId and ResponseData is having properties representing the details about the Id being sent by the client.In order to serialize this data and transfer it using SOAP, we will only add DataContract and DataMember attributes to these classes and there properties respectively.

Message Contract in WCF

Next, we will add a method in our service interface, which will take an input of type RequestData and return output of type ResponseData. Depending on the EmployeeId received in the request, it will return data of the user. So our implementation will be like the following :

Message Contract in WCF

Now, run the wcf test client, set a sample EmployeeId and invoke the method to see the results. We can see that the request and response SOAP xml’s contain the EmployeeId that we had set and its corresponding details respectively.

Message Contract in WCF

This is the normal way of sending the data through the SOAP. Sometimes we may have situation, where we need to control the way data is being sent, like we may need to send the data in the header of the SOAP or control the overall structure of what data is being sent in the header or body etc. In that case, using DataContract & DataMember is not the solution.

So let’s change some of our existing requirement and approach, where, we would like to send the EmployeeId in the header of the request xml and get back the EmployeeName, EmployeeDesignation in body of the response xml and EmployeeUserName in the header of response xml. To do this, we need to alter our RequestData and ResponseData classes slightly and decorate them with MessageContract and its related attributes named MessageHeader and MessageBodyMember attributes. For the data which we want to send in the header, we add MessageHeader attribute and for data that we want to send in body xml, we add MessageBodyMember attribute. On the whole, we add the MessageContract attribute on these classes, so that these can be serialized for transfer. So our changed code becomes :

Message Contract in WCF

So all set now. We just need to run the wcf test client and invoke the method again and we can see the results.

Message Contract in WCF

This what we changed the code for. We have the EmployeeId in request header xml and EmployeeUserName in the response header xml. Other details are added in the response body xml. But using this process has got certain restrictions on it. These are :

  • Any method involving MessageContract types, can have only one input parameter and that too has to be a MessageContract type.
  • The return value can be either be void or any type that is of MessageContract type.

So this is the basic implementation of MessageContract. If you need to control the overall structure of the SOAP xml being used, you need to use MessageContract. Hope you enjoyed reading it…!!!

Fault Exception and Fault Contract in WCF

It is quite common to use try/catch exception in our methods and display a user friendly message at the UI. Actual technical error is never displayed to the front end user. But consider the case of service oriented applications, which act as an api and provide services to the clients. If any error occurs at the service end, we can simply catch the exception and perform the required action. But what about client ? Client which uses this service, will receive a long exception message, of which he has no idea about. Also, a good application should never display error messages at the front end. WCF provides a way of handling these situations, by the use of Fault Contract.

So let’s try to understand some basics of this concept.

What is Fault Exception ?

For this, we will create 2 applications. One will be our WCF service named Demo and another is WCF client, which will consume this service. Our service will be exposing an operation to client (named DivideNumber), to divide a number by zero. This is intentionally done to raise an exception in the service operation. We will not add any try-catch block in either of the applications. So when our service is ready, then add its reference in the client application and invoke the service method DivideNumber. Now run the application and see what happens.

Fault Contract in WCF

A big bang and the yellow screen will appear. But this will not give any idea to us, about what happened in the service. So we will do, what it suggests. We go to our service web.config and navigate to the serviceBehaviors section and change the setting includeExceptionDetailInFaults to true. 

Fault Contract in WCF

By setting this property to true allows the actual exception details to be sent to the client, consuming the service. Now, update the service reference in the client application and run the application again and we can see what was the actual exception and resolve it.


The error message that gets transferred in both the cases above, is passed through the <faultstring> tag in the response SOAP xml. We can test this through the WCF Test client. Run the service test client, invoke the method and we can see the exception string in the XML generated for the SOAP response.

Case 1, includes where we have not passed the details of the exception.


Case 2, is where we have passed the actual exception to the client, by setting includeExceptionDetailInFaults to true, in service web.config


But this kind of process should be only followed for the development environment and never in production environment. The reason being, a service oriented application should never expose about what exactly is happening behind the scenes. Exposing any exception like this can expose the logic you are using in your application, to the client. Also, displaying the exceptions to the client is never a good thing. 

Although its not a good thing to send the error information to the client, but still, the client should also get to know whether the operation he called for has succeeded or not. But the point is, if our service is being used by different languages like php, JAVA etc, then passing the actual .NET based exceptions to the client, is also not feasible or advisable. So here the role of FaultException class comes into the picture. The fault exception is used to pass the custom error message from the server to the client, inside the SOAP response xml. When the response is received by the client, the custom exception message set by the service, is also available in the <fault> tag in the SOAP.

In order to do this, the service needs to throw a new instance of the FaultException class, with the custom message set in its constructor. Let’s say, we pass the custom message “Service was unable to divide by zero.” in the constructor.

Fault Contract in WCF

Now run the test client and see the response xml. The custom message that we have added, will be now carried to the client, by the <fault> tag.

Fault Contract in WCF

It is more of like adding a try-catch on the entire communication between the client and the service. Exception is caught at the service level and is propagated to the client by using throw, via SOAP message . Client catches the exception and gets the exception details.

Now, update the service reference in the client application and run again. It will display the message set by the service. Even if we keep the setting includeExceptionDetailInFaults in web.config  to true or false, it will still display the message from the FaultException class, which the service has added. So the client will never come to know how exactly your service is working, but still get to know about the status of his request. 

Fault Contract in WCF

Fault Contract and strongly typed FaultExceptions

Now that we have the know that we can send exceptions to the client, wouldn’t it be great if we could send extra information related to the exception, apart from the custom exception message or send strongly typed exceptions, with selected information. Good news is that it is possible. WCF provides us FaultContract attribute to achieve this requirement. This attribute provides the ability to create strongly typed fault exceptions or in other words, we can create different custom classes to represent different types of exceptions which we can have in our application and allow them to propagate to the client application.

To do so, we will add a new class to represent our exception type and 3 properties to it, which will represent the entire exception to the client. Our class will be named ExceptionFaultContract and properties will be StatusCode, a user defined message and its description. Next, we need to add DataContract and DataMember attributes to this class.

Fault Contract in WCF

To pass this class as a strongly typed FaultException for this method, we need to add the FaultContract attribute on our method and specify its type using typeof expression. It is like List<String> represents a generic List of string type, setting the typeof property represents the FaultException of the type ExceptionFaultContract. This is what is meant by strongly typed FaultException.

It is mandatory to provide the typeof property with FaultContract. Also, if no fault contract attribute is applied, the default exception that will be returned by wcf will be of type FaultException.

Fault Contract in WCF

Our method implementation will now also change slightly to catch the exception and return the custom fault exception in the form of ExceptionFaultContract. For strongly typed fault exceptions, FaultException class uses FaultException<TDetail>, where TDetail represents the custom type. Compare this with the example of List<string> that we discussed above. So our code becomes like :

Fault Contract in WCF

Run the wcf test client and invoke the method. We can see the details of the custom message that we had set.


Now in the client application, we will catch the exception using the reference of this exception type defined in the service. Run the application and see the exception. This exception fault will be accessible through the Detail property of the FaultException instance.

Fault Contract in WCF

So we can see the details of the exception, that we had set in the service.

Why use FaultExceptions ?

This type of solution is very helpful in situations where client and server are of different platforms. For ex, you might have client applications in JAVA or php. So, if there is any .NET specific exception in the service, we can’t send the fault exception to the client directly, as client will have no about .NET based exceptions. They only need to know that an exception has occurred and if possible, a reason for the same. So it becomes very important to use FaultExceptions normally only or use the strongly typed fault exceptions.

So this was all about the basic concept of WCF fault exceptions and fault contracts. Hope you enjoyed reading it.