Reputation: 95
As everyone known c# is strongly typed language.
This have the pros and cons.
I have this code that work fine without problems:
public static void SetText(Button Obj, string Text) { Obj.Text = Text; }
public static void SetText(CheckBox Obj, string Text) { Obj.Text = Text; }
public static void SetText(ComboBox Obj, string Text) { Obj.Text = Text; }
public static void SetText(Label Obj, string Text) { Obj.Text = Text; }
public static void SetText(LinkLabel Obj, string Text) { Obj.Text = Text; }
public static void SetText(RadioButton Obj, string Text) { Obj.Text = Text; }
public static void SetText(TextBox Obj, string Text) { Obj.Text = Text; }
public static String GetText(Button Obj) { return Obj.Text; }
public static String GetText(CheckBox Obj) { return Obj.Text; }
public static String GetText(ComboBox Obj) { return Obj.Text; }
public static String GetText(Label Obj) { return Obj.Text; }
public static String GetText(LinkLabel Obj) { return Obj.Text; }
public static String GetText(RadioButton Obj) { return Obj.Text; }
public static String GetText(TextBox Obj) { return Obj.Text; }
The easy way to reduce this code is something like this:
public static void SetText(Object Obj, string Text) { Obj.Text = Text; }
public static String GetText(Object Obj) { return Obj.Text; }
but is don't work becouse c# is a strict language about the type.
To solve the problem I could use reflections but I don't want do it.
If there is an altenative I can reduce much code otherwise I must do it for other functions.
Some idea ?
Upvotes: 0
Views: 195
Reputation: 23626
Dmitry's answer is great and I just was in extend it little bit.
Assuming you have non-trivial logic in each method (because why do you need them, if you can access Text
property on Control
class directly), you can take advantage of extension methods in C#. They where added since C# 3.0
version
public static class ControlExtensions
{
public static void SetText(this Control ctrl, string text)
{
ctrl.Text = text;
}
public static String GetText(this Control ctrl)
{
return ctrl.Text;
}
}
In case of simple static methods, you call would look like:
YourStaticClass.SetText(myControl, "some text");
but using extension method syntax, you can write next code on any object, derived from Control
class.
myControl.SetText("some text");
and the static method SetText
will be called
Upvotes: 0
Reputation: 6301
Every element in your code is derived from Windows.Forms.Control
which has a Text
property.
public static void SetText(Control ctrl, string text) { ctrl.Text = text; }
public static String GetText(Control ctrl) { return ctrl.Text; }
(Note that the standard .NET naming conventions recommend using lowercase names for parameters.)
Upvotes: 11