Generic built-in EventArgs to hold only one property? - c#

I have a number of EventArgs classes with only one field and an appropriate property to read it:
public class SomeEventArgs : EventArgs
{
private readonly Foo f;
public SomeEventArgs(Foo f)
{
this.f = f;
}
public Foo Foo
{
get { return this.f; }
}
}
Is there any built-in, generic class to implement such behavior or I have to roll my own?
public class GenericEventArgs<T> : EventArgs
{
private readonly T value;
public GenericEventArgs(T v)
{
this.value = v;
}
public T Value
{
get { return this.value; }
}
}
P.S.
I wrote a suggestion on Microsoft Connect

If there is one, it certainly isn't well publicised! (i.e. it's not something you're meant to use for general purpose stuff, like Func<T>.) I've thought about the same thing myself before now. It's not a rare requirement, IMO.
One downside of this is that it doesn't have a meaningful name for the property, of course - it's like an EventArgs equivalent of Tuple. But if you have several different use cases for this and it will actually be obvious what the meaning is, go for it :)

On this page at bottom you can see all classes are inherited from EventArgs class:
http://msdn.microsoft.com/en-us/library/system.eventargs.aspx
The most appropriate is ReturnEventArgs http://msdn.microsoft.com/en-us/library/ms615572.aspx but this class is located in PresentationFramework.dll, that is only referenced by WPF projects.
So I recommend to create your own one.

I do not think there is.
Looks like you are not the only one to ask himself this question.
Take a look here

Related

c# getters setters style

I'm working on some code where there is lots of code like this:
private int x;
public void SetX(int new_x)
{
this.SetXValue(new_x);
}
private void SetXValue(int new_x)
{
this.x = new_x;
}
and similarly with properties:
private int x;
public int X
{
get { return this.GetX(); }
}
private int GetX()
{
return this.x;
}
What i don't get is why the need for the private methods which do the actual work, i.e. why not just have methods like this instead:
public void SetX(int new_x)
{
this.x = new_x;
}
public int X
{
get { return this.x; }
}
is it just the other persons personal choice or is there some good reason for using the first way?
(i typed above code manually so sorry if any mistakes but you should hopefully see what i'm trying to say)
Cheers
A
There's no reason for code like that as far as I can see. If you're not doing anything with the new values (like processing/checking before storing) and you're writing C# 3.0 you can actually just shorthand it it to this:
public int MyProperty { get; set; }
The compiler creates the backing store for you and you can just reference:
this.MyProperty
...inside your class. You can also create get-only properties like:
public int MyProperty { get; private set; }
All of which I think is pretty neat!
Why don't you use the Getters and Setters directly to implement your logic? I don't understand the need for additional methods unless you have extra parameters that influence the setter's behavior:
private int myVar;
public int MyProperty
{
get
{
return myVar;
}
set
{
myVar = value;
}
}
public void SetMyPropertySpecial(int a, string reason)
{
Console.WriteLine("MyProperty was changed because of " + reason);
this.myVar = a;
}
Update:
Indeed, this person seems to like having more lines of code, but the structure is utterly useless. Stick to .NET standards using Getters and Setters (see MSDN)
No, there is no reason for doing this, it looks liks someone was paid by lines of code.
So, yes, you're right, this is just the other persons personal choice, and it's not a very good one.
A general rule of thumb is to use properties for simple get/set operations and get/set methods when there is a relevant part of logic needed to get/set a value (e.g. validation during set or database access during get).
So if the actual code is really as simple as in your example just use properties and do the work in their getters/setters.
If the actual code is more complex replace the properties (at least the setters) by methods as in your third example.
One possible reason would be that the properties can have login that should be executed only when the property is set externally and calls from inside the class do not execute the whole logic but only the logic in the private method. Of course it makes no sense to make these methods in advance because introducing them later will not change the contract of the class. Chances are that whoever wrote this code was new to C# and did not understand what properties do.
I think it must be an old Java developper that did this.
The .Net way is
private int _foo;
public int Foo
{
get
{
return _foo;
}
set
{
_foo = value;
dostuff();
}
}
That's very bizarre, there's no justifiable reason for doing that. Please refactor that code. There's also no need for a SetX method as setter can be included in properties. e.g.:
public int X {get; set;}
i may be missing something here, but this looks a bit mad to me!
You can achieve the same by either using automatic properties or properties with backing fields. here's a good description of both: http://weblogs.asp.net/dwahlin/archive/2007/12/04/c-3-0-features-automatic-properties.aspx
Yes, that is fine only if the SetValue is private or protected and is doing more than just setting a value.
I am working on a project where we do a lot of those things. That is because we are doing more than just setting a value (value checks, state checks etc.)
Having a public setter and a public SetValue does not make sense at all and will confuse your consumers as to what setter to use.
Here is another scenario where we use this kind of design:
public abstract class A{
protected virtual void SetValue(object value);
public object SomeObject{
set{SetValue(value);}
}
}
In this case, we want class A to delegate setting/checking that value to whatever class inheriting from it.

Is this the example of polymorphism?

I kinda know what polymorphism is but failed to understand it clearly. Also my code is following:
class Human
{
public virtual void CleanTheRoom()
{
}
}
class Woman:Human
{
public override void CleanTheRoom()
{
//women clean faster
}
}
class Man:Human
{
public override void CleanTheRoom()
{
//men clean slower, different code here
}
}
class Child:Human
{
public override void CleanTheRoom()
{
//empty ... children are lazy :)
}
}
Should I explain this is polymorhism because all derived classes from base class Human contain method CleanTheRoom but each of them it implements differently?
The benefit of polymorphism comes when you want to invoke the method on some type of Human, but you don't care which one specifically.
By having CleanTheRoom() defined at the base class level, Human, you can write shorter, cleaner code elsewhere in your application whenever you are working with an instance of Human, whether it be a Child or otherwise.
Polymorphism, for example, lets you avoid lengthy conditional statements where you explicitly check for each type of Human and call a different method:
Good:
private void SomeMethod(Human h)
{
//some logic
h.CleanTheRoom();
//more logic
}
Bad:
private void SomeMethod(Human h)
{
//some logic
if (h is Adult)
CleanTheRoom();
else if (h is Child)
GoofOff();
//some logic
}
What you have is a good example of inheritance. Polymorphism refers specifically to being able to refer to objects of different types by using a single type (the parent class or interface), something this type of inheritance makes possible. Like so:
List<Human> humans = new ArrayList<Human>();
humans.add(new Woman());
humans.add(new Woman());
humans.add(new Man());
humans.add(new Child());
humans.add(new Child());
foreach(Human hum in humans) {
hum.CleanTheRoom(); //I don't know the type of hum, but I don't care
}
Say I've been collecting instances of Human from various locations -- I don't know what type each one is. But I can still iterate over them and call CleanTheRoom(), because they share a parent class.
I'll add a real-world example. Say I have an Invoice class with various subclasses for different types of Invoices -- maybe there are different kinds of Invoices for service clients versus customers who make one-time purchases. Sometimes I care deeply about the differences, and I only deal with one type. But sometimes I want to loop through all of the invoices for this month and print them out. If the parent class has a print() method (which may well be implemented differently by different types) then I can do that.
Yes, that is correct. And you can call the method CleanTheRoom() without knowing which "kind" of human is it.
Here you have some basic examples.
I think you fail to see the benefit, that's the key you're missing to fully understand polymorphism. I will try to make an example:
Let's say you have a simple CRUD form. This is the code of the save button:
var Client = PopulateDTO(); //put all the values in the controls, to an object
if(Action==Actions.Create){
_repository.Create(Client);
}
else if(Action==Actions.Update){
_repository.Update(Client);
}
else if(Action==Actions.Delete){
_repository.Delete(Client);
}
this.Close();
This code works, but it's bad code, and difficult to read. Let's use polymorphism (and the strategy pattern):
public abstract class BaseStrategy{
abstract void Do(ClientDto Client);
}
public class CreateStrategy:BaseStrategy{
public override void Do(ClientDto Client){
_repo.Save(Client);
}
}
public class UpdateStrategy:BaseStrategy{
public override void Do(ClientDto Client){
_repo.Update(Client);
}
}
public class DeleteStrategy:BaseStrategy{
public override void Do(ClientDto Client){
_repo.Delete(Client);
}
}
So, we have an abstract class, and 3 implementations, each one doing something with the client object. Now, the code of the save button in the form will be:
BaseStrategy stg = GetCorrectStrategy();
var Client = PopulateDTO();
stg.Do(Client);
this.close;
And the method GetCorrectStrategy() will instantiate the correct Strategy implementation, depending if the user is creating, editing or deleting the client.
I hope this answer will help you. But if didn't help you, I suggest you read about strategy pattern, It's one of the best uses of polymorphism in my opinion
Since several people have already given fine examples of polymorphism, I'll offer a different perspective that really helped me to grok it.
In functional programming, functions are the first class concepts in contrast to OOP where objects are supreme.
Polymorphism is to OOP what pattern matching is to FP. Here is a function that uses pattern matching (using an ML style syntax).
let f x =
match x with
| T -> //do stuff with a T to return some value
| S -> //do stuff with an S to return some value
| U -> //do stuff with a U to return some value
| V -> //do stuff with a V to return some value
So when you use the function f, you can pass it an object of either type T, S, U, or V. In strongly typed FP languages like F#, the type of x is denoted T|S|U|V. Such types are commonly referred to as Sum types or Tagged Unions.
If we fix up your example to make Human an abstract class, then it will become clear that polymorphism in OOP just gives you a way of expressing a sum type.
Thus, CleanTheRoom is a function that takes a type Human. But Human is just the name for the type Man|Woman|Child which is a sum type. The big difference between languages like C# and functional languages like F# is that one treats objects as top level things while the other treats functions as top level things. Also, everything in OOP languages like C# must have names. In a functional language we could denote the type Man|Woman|Child without having to explicitly name it.
The key is not to think of the code as having different CleanTheRoom methods, but rather think of CleanTheRoom as one method that takes a type Man|Woman|Child (which is named Human). Polymorphism is just the implementation detail.
In summary, polymorphism (especially with abstract classes) basically just give you a way to name sum types and do pattern matching.
See:
http://en.wikipedia.org/wiki/Tagged_union
http://en.wikipedia.org/wiki/Algebraic_data_type
An example in C#:
This is my class file
class parent
{
public virtual string saySomething(string s)
{
return s+":Parent";
}
}
class man : parent
{
public override string saySomething(string s)
{
return s+":Man";
}
}
class woman : parent
{
public override string saySomething(string s)
{
return s+":Woman";
}
}
class child : parent
{
public override string saySomething(string s)
{
return s+":Child";
}
}
Create Four Buttons and a label.
Here is the implementation on a simple form1
private void Form1_Load(object sender, EventArgs e)
{
p1= new parent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = p1.saySomething("I am parent!");
}
private void button2_Click(object sender, EventArgs e)
{
p1 = new man();
label1.Text = p1.saySomething("I am man!");
}
private void button3_Click(object sender, EventArgs e)
{
p1 = new woman();
label1.Text = p1.saySomething("I am woman!");
}
private void button4_Click(object sender, EventArgs e)
{
p1 = new child();
label1.Text = p1.saySomething("I am child!");
}
Is it run-time polymorphism?
P1 is an object. Depending upon the situation (Context), a button click, it is executing different piece of code. So, p1 is behaving differently depending upon the click event.
class Program
{
static void Main(string[] args)
{
List<ICleanTheRoom> cleanerList = new List<ICleanTheRoom>
{
new Child(),
new Woman(),
new Man()
};
foreach (var cleaner in cleanerList)
{
cleaner.CleanTheRoom();
}
}
}
internal interface ICleanTheRoom
{
void CleanTheRoom();
}
// No need for super type
//class Human : ICleanTheRoom
//{
// public virtual void CleanTheRoom()
// {
// }
//}
internal class Woman : ICleanTheRoom
{
public void CleanTheRoom()
{
throw new NotImplementedException();
}
}
class Man: ICleanTheRoom
{
public void CleanTheRoom()
{
throw new NotImplementedException();
}
}
class Child: ICleanTheRoom
{
public void CleanTheRoom()
{
throw new NotImplementedException();
}
}
Is it a new object created each time at runtime, clearly inheriting but no polymorphing.

Multiple inheritance in C# - again

I know that C# does not offer multiple inheritance. And I know there' are workarounds like this one for instance.
But here's a problem that I faced today, can't figure any ELEGANT workaround. I'll add some abstract code-sample so you get it quicker...
(let it be a real-life ASP.NET code - cause those "class A, class B" code-samples are really confusing):
public class AdminPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
//if not an admin - get out
if(!CurrentUserIsAdmin()) Response.End();
base.OnInit (e);
}
}
public class JQueryPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
RegisterJQueryScript();
base.OnLoad (e);
}
}
//now here's what I REALLY miss in C#
public class AdminJQueryPage : AdminPage, JQueryPage;
Compose out the functionality? This is better for Single Responsibility. You'd have to think carefully about your constructors.
interface IAdminPage {
public string AdminPageMethod();
}
interface IJQueryPage {
public string JQueryPageMethod();
}
internal class AdminPage : IAdminpage {
private string someString;
internal AdminPage(string value) {
this.someString = value;
}
public string AdminPageMethod() {
return "AdminPage result with some string: " + this.someString;
}
}
internal JQueryPage : IJQueryPage {
private int someNumber;
internal JQueryPage(int value) {
this.someNumber = value;
}
public string JQueryPageMethod() {
return "JQueryPage result with number: " + this.someNumber;
}
}
class AdminJQueryPage : IQueryPage, IAdminpage {
private readonly IAdminPage adminPage;
private readonly IJQueryPage jqueryPage;
public AdminJQueryPage(string someString, int someNumber) {
this.adminPage = new AdminPage(someString);
this.jqueryPage = new JQueryPage(someNumber);
}
public string AdminPageMethod() {
return this.adminPage.AdminPageMethod();
}
public string JQueryPageMethod() {
return this.adminPage.JQueryPageMethod();
}
}
If you really want multiple inheritance, look at Scala's traits
Edit: added passing of constructor values to composed out classes. Also made the classes internal (cannot be accessed or constructed outside the assembly) because they are only ever constructed by the AdminJQueryPage class, which is the 'public-facing' class.
I came from C++ too and dont miss it, especially since reading Refactoring [and using a non-OOTB tool for that].
You can use PostSharp to post process based on placing attributes on your AdminJQueryPage which would achieve the exact same effect.
Or you can Extract Method code into helper classes and call that (i.e., Joe's example)
Or you can put the helpers in a single base class and call from that.
Either way your code will be clearer.
It's only a matter of time before your mixins start overlapping, and then your general suite of techniques for managing that complexity needs to kick in - in C++, MI should only have been one tool in a suite - rather than a very sexy hammer.
its possible to fake a mixin by specifying a interface and creating extension methods for that interface. however I'm not use this will help overriding methods, only adding new ones. you are of course able to then call an extension method when overriding, but that is basically the same as extracting the methods to a helper class, but with a little more sugar
Even if it was possible, one problem with the semantics of an MI-based solution to the specific problem you raised is what happens on the markup side? The Render() method that generates the markup would run first in one class, and then in the other? That's probably not the behavior you want when both classes generate entire pages.
If you're open to solutions that are outside of the language itself, there are several elegant options in ASP.NET that will address the type of issue you raised (changing the actions taken during an event in the page life cycle). For example:
Page Adapters
Control Adapters
Custom user controls
HttpModules
Master Pages
Tag mapping
The best choice will of course depend on the details of your application. In case it's helpful, I cover those options in my book, including sample code: Ultra-Fast ASP.NET.
The simplest approach is to build a hierarchy - allow AdminPage to inherit from JQueryPage like so:
public class AdminPage : JQueryPage
{
protected override void OnInit(EventArgs e)
{
//if not an admin - get out
if(!CurrentUserIsAdmin()) Response.End();
base.OnInit (e);
}
}
public class JQueryPage : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
RegisterJQueryScript();
base.OnLoad (e);
}
}
//now here's what I REALLY miss in C#
public class AdminJQueryPage : AdminPage
My guess is some of this awkwardness comes from the ASP.NET page model, which uses overridden base class methods.
You can to do this with Interfaces
public interface IJQueryPage
{
}
public abstract class AdminPage : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
//if not an admin - get out
if(!CurrentUserIsAdmin()) Response.End();
base.OnInit (e);
}
protected override void OnLoad(EventArgs e)
{
if (this is IJQueryPage)
{
RegisterJQueryScript();
}
base.OnLoad (e);
}
}
public class AdminJQueryPage : AdminPage, IJQueryPage
{
}

C# WinForm with different Types?

I have a form which encapsulates all the functionality, but works with a concrete Type T1.
Now I want to create the same form with the difference, that it will use another Type T2.
T1 and T2 don't inherit from anything, so I can't use inheritance.
How could I do that without copying the whole code again and again?
I was thinking about creating a generic Form, but I don't think that's a correct solution.
Any ideas?
Write T2, copy all of the code and make sure to encapsulate all the differences in separate methods. Then create a new base class and move the common code from both. A code-sharing design becomes much more obvious (including whether you should use generics) after you have two classes which need it, rather than trying to plan ahead.
What do you do with T1 and T2 in the form? If you want to expose/accept values in a strongly typed way, generics sounds like exactly the right approach - although it can be tricky with the WinForms designer, IIRC.
To put it another way: if you weren't using WinForms, would you reach for generics?
I use a generic element to encapsulate my object, this has a text value and a tag value, it allows for things like what you're trying to do, one good use is for adding to a combo box. Maybe you could incorporate something like this into your form?
public class GenericElement<T> {
public GenericElement(string text) {
this.Text = text;
}
public GenericElement(string text, T tag) : this(text) {
this.Tag = tag;
}
public T Tag {
get; set;
}
public string Text {
get; set;
}
public override string ToString() {
return Text;
}
}
// Combo-Box example
public class MyForm : Form {
private void DoLoad(object sender, EventArgs e) {
comboNum.Items.Add(new GenericElement<int>("One", 1);
comboNum.Items.Add(new GenericElement<int>("Two", 2);
comboNum.Items.Add(new GenericElement<int>("Three", 3);
}
public int SelectedNumber {
get {
GenericElement<int> el =
comboNum.SelectedItem as GenericElement<int>;
return el == null ? 0 : el.Tag;
}
}
}

How can one type access a private setter of another type's property?

All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}
You have a design flaw. Also, don't be paranoid about data hiding. Here's 3.5's way to do it:
class Program
{
static void Main(string[] args)
{
Managed m = new Managed();
Console.WriteLine(m.PrivateSetter);
m.Mgr.SetProperty("lol");
Console.WriteLine(m.PrivateSetter);
Console.Read();
}
}
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
}
public class Manager
{
private Action<string> _setPrivateProperty;
public Manager(Action<string> setter)
{
_setPrivateProperty = setter;
}
public void SetProperty(string value)
{
_setPrivateProperty(value);
}
}
Here's how we'd do it in pre-lambda days:
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(this)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
public class Manager
{
public void SetProperty(string value)
{
m.PrivateSetter = value;
}
private Managed m;
public Manager(Managed man)
{
m = man;
}
}
}
The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
get { return foo; }
set { foo = value; }
}
When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.
You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
get{ return _name; }
protected set { _name = value; }
}
keep in mind that the set method of the property is only accessible from the derived class.
Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.
You could do:
public void setMyProperty(int value, Object caller)
{
if(caller is MyManagerClass)
{
MyProperty = value;
}
}
This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!
You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...
Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
private int count;
public int Count
{
get { return this.count; }
private set { this.count = value; }
}
}
public static class WidgetManager
{
public static void CatastrophicErrorResetWidgetCount( Widget widget )
{
Type type = widget.GetType();
PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
info.SetValue(widget,0,null);
}
}
The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {
internal MyItemManager manager { get;set; }
public string Property1 {
get { return manager.GetPropertyForItem( this ); }
}
}
Unfortunately this isn't great design either.
What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality. There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.
If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value. The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object. Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>. The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate. Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate. Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).
if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)

Categories