Thursday, February 23, 2012

How to use default parameter in C# 2.0 & 3.5

For example, I need a method like this:

public void InitData(int index, object value, bool required = false) {}

I can write it as:

using System.Runtime.InteropServices;public void InitData(int index, object value, [Optional, DefaultParameterValue(false)] bool required) {}

The attribute Optional tells compiler that the parameter required has default value. And the attribute DefaultParameterValue(false) tells compiler what is the default value.

Very simple. Isn’t it?

No comments:

Post a Comment