Reputation: 23
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
Reputation: 564413
You need to do two things to make this work:
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
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