C# Parametrized Property

I am currently working on a project where I have to convert some VB.NET code to C#. One of the problems is some of the VB:s features that are not supported on C#, like parameterized properties.

I also wanted to be able to create C# code that is usable in VB in the same way it was earlier. Since parameterized properties are not supported in C# the first impression was to create getter and setter functions but this is clunky in VB and breaks old code which assumes accessing a variable/data in a certain manner.

After some wondering and not accepting defeat by C# I came up with a solution.

It requires the following steps:

  1. Create a new class that represents the property
  2. Use this keyword with [] operator to assign a get and set property (the class will function as the property itself)
  3. To use functionality from the parent class you force the property class with a reference to the parent class. After this, you are able to access functionalities from the parent class as long as the visibility is set to public.

Here is the code:


public class PropertyName
{
 private PartenClass refPartenClass = null;
 public PropertyName(refPartenClass parentClass)
 {
 if (parentClass == null)
 throw new Exception("parent class parameter can not be null");

 this.refPartenClass = parentClass;
 }

 public string this[string path, String DefaultValue = ""]
 {
 get
 {
 PartenClass item = null;
 item = this.refPartenClass.LocateItem(path, false);
 if (item == null)
 {
 return DefaultValue;
 }
 else if (string.IsNullOrEmpty(item.ItemValue))
 {
 return DefaultValue;
 }
 else
 {
 return item.ItemValue;
 }
 }
 set
 {
 PartenClass item = null;
 item = this.refPartenClass.LocateItem(path, true);
 item.ItemValue = value;
 }
 }
}

This is then how you use it:

  1. Create a declaration of the property class as a property itself
  2. Instantiate it during the ParentClass constructor and pass the parent as reference

public class ParentClass
{
public PropertyName Value { get; set; }

private void InitializeParametrizedProperties()
 {
 this.Value = new PropertyName(this);
 }
public ParentClass()
 {
 this.InitializeParametrizedProperties();
 }

}

Btw, nothing stops you from overloading the this[] definition to accept a different kind of parameters and return values. Just be careful with the same kind of parameter definitions. The compiler won’t know what to call.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s