PMCastle
PMCastle

Reputation: 23

Custom properties generics at runtime

I am using the next code to pass parameters to a generic method.

 private void SetValue<T>(T control, String title)
 {
      T.BackgroundImage = title;
 }

example usage

SetValue<Button>(myButton,"Resource.ImgHouse_32.etc")

this doesnt compile due at the line T.BackgroundImage, its is a property of some controls, Button, Checkbox, etc.

how can I to set a generic way for can do it T.BackGroundImage ?

sorry any error is code in the fly.

Upvotes: 1

Views: 49

Answers (2)

Reed Copsey
Reed Copsey

Reputation: 564413

You need to do two things to make this work:

  1. Constrain your generics (or remove them), and
  2. Load the resource from the string

This would look like:

private void SetBackgroundImage<T>(T control, string title) where T : Control
{
    control.BackgroundImage = 
                new Bitmap(
                    typeof(this).Assembly.GetManifestResourceStream(title));
}

Note that, in this case, you don't need generics at all. Since Control has the BackgroundImage property, you can just write this as:

private void SetBackgroundImage(Control control, string title)
{
    control.BackgroundImage = 
                new Bitmap(
                    typeof(this).Assembly.GetManifestResourceStream(title));
}

You could then call this via:

SetBackgroundImage(myButton, "MyProject.Resources.ImgHouse_32.png"); // Use appropriate path

Upvotes: 3

m0s
m0s

Reputation: 4280

 private void SetValue<T>(T control, String title) where T:Control

You have to tell the compiler that T inherits Control. This is called constraints I believe, and you can set this constraints to classes and interfaces.

http://msdn.microsoft.com/en-us/library/vstudio/d5x73970.aspx

Upvotes: 1

Related Questions