What is the meaning of a delegate inside a class? - c#

I understand delegates as a shortcut for defining a class with one method but what is the meaning of bar2 below? It compiles. But I can't see what an inner class would do here. I know I'm missing something so that's why I'm asking (this is not homework, I'm at work-work right now).
namespace ns2 { public delegate void bar();}
public class foo
{
private ns2.bar _callback;
public foo(ns2.bar callback) { _callback = callback; }
public void baz() { _callback(); }
public delegate void bar2();
}
Thanks!

To add to Jon and Jared's answers, I note that the only time you'd usually define a delegate inside a class is if the delegate were a private implementation detail of the class. It is rare and bizarre to have a public delegate definition inside a class.
For example, consider my favourite pattern: an abstract base class that can only be extended by private nested classes that are manufactured with factories:
public abstract class Animal
{
private Animal() { } // prevents subclassing from outside!
private sealed class Giraffe : Animal { }
private sealed class Leopard : Animal { }
public static Animal GetGiraffe( ) { return new Giraffe(); }
public static Animal GetLeopard( ) { return new Leopard(); }
Suppose an implementation detail of Animal was that you needed to have a delegate from Giraffe to Leopard:
private delegate Leopard D(Giraffe g);
This cannot be a public delegate class because it refers to private types!
Nowadays of course you wouldn't even do this. You'd use Func<Giraffe, Leopard> and you're done.
Therefore, the nested delegate type is pretty much there for completeness and backwards compatibility these days; normally you wouldn't use it.

Delegates are not shortcuts for defining a class with one method. They in fact have at a minimum 6 methods (Invoke, BeginInvoke, EndInvoke, GetHashCode, Equals, ToString).
One reason for the pattern of putting delegates inside a type is to avoid global namespace pollution. The delegate bar2 is only accessible through a qualified reference from foo. This can be valuable if bar2 is a name which has multiple valid meannings and putting it within foo provides necessary context.

It's just declaring a nested type, that's all. As it's public, there's pretty much no difference between that being declared inside the type and being declared outside.
Other classes will have to refer to it via the name of the containing type (unless they have a using directive specifically for it):
public class OtherClass
{
private void DoSomething()
{
foo.bar2 action = delegate { ... };
foo f = new foo(action);
...
}
}
Usually when I write a nested type, it's private - it's just a helper class for the containing class; an implementation detail. That doesn't have to be the case, of course, but it should at least be true that the nested type is meaningless unless you're in some way using the outer class. For example, it could be a builder for the outer class, or an enum used in some parameters for a method call within the outer class.
(By the way, it's useful when writing sample code like this to follow .NET naming conventions even for meta-syntactic names like Foo and Bar. It makes the difference between variables and types clearer, for example.)

Related

How to reference abstract class

When posting this question my hope was to find a way how to reference/point to
an abstract class that that could be used by a worker/holder.
As the comments by #progman suggested and #laryx-decidua there is no way to hold a reference to an abstract class, but one can only hold a reference to a instantiated object.
Below you can find what I think is their proposed solution. To me this is an ugly solution, and I would have liked to have one that derives multiple static classes from an abstract base class and the holder gets references to those static classes to do its work. Deriving a static class form an abstract class Why you can't drive a static class is it seems prohibited by design and indicates bad architecture; although I don't see why the solution above is any better.
Suggested Solution
using System;
using System.Collections.Generic;
public abstract class BaseClass
{
// Some declarative knowledge
public int value;
protected BaseClass(int value){
this.value = value;
}
// Some procedural
public abstract void execute();
}
public class ConcreteClass1 : BaseClass
{
public ConcreteClass1() : base(42) {}
public override void execute()
{
Console.WriteLine("In Concrete1! Value " + value);
}
}
public class ConcreteClass2 : BaseClass
{
public ConcreteClass2() : base(8888) { }
public override void execute()
{
Console.WriteLine("In Concrete2! Value " + value);
}
}
public class Holder
{
BaseClass activeClass;
public void setClass(BaseClass newClass){
activeClass = newClass;
}
public void doWork()
{
int x;
activeClass.execute();
x = activeClass.value * activeClass.value;
Console.WriteLine("Holder has done its work: " + x);
}
}
class MainClass
{
static void Main(string[] args)
{
List<BaseClass> classes = new List<BaseClass>();
classes.Add(new ConcreteClass1());
classes.Add(new ConcreteClass2());
Holder holder = new Holder();
holder.setClass(classes[0]);
holder.doWork();
holder.setClass(classes[1]);
holder.doWork();
holder.setClass(classes[0]);
holder.doWork();
}
}
producing
In Concrete1! Value 42
Holder has done its work: 1764
In Concrete2! Value 8888
Holder has done its work: 78996544
In Concrete1! Value 42
Holder has done its work: 1764
Disclaimer: I don't speak C#, but I suspect the situation is similar to C++. The rest of the answer is based on my C++ and general OOP experience.
If I understood you correctly, you'd like to hold derived class object(s) through a base class reference and invoke a polymorphic ("virtual") method on those objects. Because you expect those derived classes to be "stateless" (i.e. no data members), you thought maybe you could "get away with" static (and/or abstract) classes.
The problem is that you need to instantiate something to put into your Holder objects, because a reference (or a pointer) can refer to (point to) only to a concrete object. So you need to instantiate objects that will be referred to via a reference in Holder, as some of the commenters have already pointed out. That's why abstract classes won't do -- they cannot be instantiated.
If there were an OOP language that supports references to types , plus some mechanism that can do the following: "Hmm, here is a reference AnimalTypeRef to the (possibly abstract) base class type Animal. AnimalTypeRef actually refers to the derived class type Elephant. Now, the user wants to invoke a virtual method Animal::make_noise() that does not use any class state, so let's invoke the corresponding method Elephant::make_noise() that overrides it and returns this :-)." -- well, then you could do what you have asked for.
I suspect this has not been implemented in C++ or C# because there are not too many use cases for it, and actually the same thing can be done with the general mechanism that requires that references refer to concrete objects.
Just go ahead and derive concrete (non-abstract) classes from your abstract base class, and don't worry about their statelessness. It's perfectly OK to define and use concrete objects that have no data members. Instantiate them, then initialise a Holder object with them, using a reference to the (abstract) base class and that's it. Polymorphic method invocation through base class references will do the rest.

Return MyNestedClass<K> when MyNestedClass is not MyNestedClass<K>?

Breaking down the MS RBTree (an internal .Net abstract class), I have discovered that one method returns TreePage<K>:
private TreePage<K> AllocPage(int size)
{
...
}
Within the method, variables are declared as TreePage...but the class is not defined that way:
private sealed class TreePage
{
...
}
Yet, when I mimic the code and definition using .Net 2010 (Express), I cannot do this:
Error: The non-generic type
'RBTree.TreePage' cannot be used
with type arguments
So, is there an extension method that I can't find? Is there something MS is doing that we just don't get to see?
When you declare a class nested in a generic class
class Foo<T>
{
class Bar
{
}
}
this gets compiled to a class
Foo<T>
and a class
Foo+Bar<T>
Bar is generic, because it is nested in the generic class Foo. But the type parameter declaration is not repeated in C# (where you refer to the class as Foo<T>.Bar).
I noticed that Reflector shows the generic type parameter for classes nested in generic types, even if they don't have declared any type parameters directly. That's a bug. You need to fix the code when copy it straight out of Reflector.
It's actually less complicated than you might imagine. Klass and Klass<T> are two completely different types. To wit:
class A
{
}
class A<T>
{}
class Program
{
static public void Main(string[] args)
{
A a = new A();
A<int> generic_a = new A<int>();
}
}
There's another TreePage<T> floating around there somewhere.

Is generic constructor in non-generic class supported?

Is it not supported, is it supported but I have to do some tricks?
Example:
class Foo
{
public Foo<T1,T2>(Func<T1,T2> f1,Func<T2,T1> f2)
{
...
}
}
the generics are only used in constructor, there is no field/property depended on them, I use it (generics) to enforce the type correlation for f1 and f2.
Remark: I found the workaround -- static method Create, but anyway I am curious why I have problem with straightforward approach.
No, generic constructors aren't supported in either generic or non-generic classes. Likewise generic events, properties and finalizers aren't supported.
Just occasionally I agree it would be handy - but the syntax would look pretty awful. For example, suppose you had:
public class Foo<T> {}
public class Foo
{
public Foo<T>() {}
}
What would
new Foo<string>()
do? Call the generic constructor of the non-generic class, or the normal constructor of the generic class? You'd have to differentiate between them somehow, and it would be messy :(
Likewise, consider a generic constructor in a generic class:
public class Foo<TClass>
{
public Foo<TConstructor>() {}
}
How would you call the constructor? Hopefully we can all agree that:
new Foo<string><int>()
is pretty hideous...
So yes, semantically it would be occasionally useful - but the resulting ugliness counterbalances that, unfortunately.
Generic constructors are not supported, but you can get around this by simply defining a generic, static method that returns a new Foo:
class Foo
{
public static Foo CreateFromFuncs<T1,T2>(Func<T1,T2> f1,Func<T2,T1> f2)
{
...
}
}
which is used like this:
// create generic dependencies
var func1 = new Func<byte, string>(...);
var func2 = new Func<string, byte>(...);
// create nongeneric Foo from dependencies
Foo myFoo = Foo.CreateFromFuncs<byte, string>(func1, func2);
Here is an practical example about how you would like to have extra constructor type parameter, and the workaround.
I am going to introduce a simple RefCounted wrapper for IDisposable:
public class RefCounted<T> where T : IDisposable
{
public RefCounted(T value)
{
innerValue = value;
refCount = 1;
}
public void AddRef()
{
Interlocked.Increment(ref refCount);
}
public void Dispose()
{
if(InterlockedDecrement(ref refCount)<=0)
innerValue.Dispose();
}
private int refCount;
private readonly innerValue;
}
This seems to be fine. But sooner or later you would like to cast a RefCounted<Control> to RefCounted<Button> whilst keep both object reference counting, i.e. only when both instances being disposed to dispose the underlying object.
The best way is if you could write (like C++ people can do)
public RefCounted(RefCounted<U> other)
{
...whatever...
}
But C# does not allow this. So the solution is use some indirection.
private readonly Func<T> valueProvider;
private readonly Action disposer;
private RefCounted(Func<T> value_provider, Action disposer)
{
this.valueProvider = value_provider;
this.disposer = disposer;
}
public RefCounted(T value) : this(() => value, value.Dispose)
{
}
public RefCounted<U> Cast<U>() where U : T
{
AddRef();
return new RefCounted<U>(() => (U)(valueProvider()),this.Dispose);
}
public void Dispose(){
if(InterlockedDecrement(ref refCount)<=0)
disposer();
}
If your class have any fields that are of generic type, you have no choice but to put all those types to the class. However, if you just wanted to hide some type from the constructor, you will need to use the above trick - having a hidden constructor to put everything together, and define a normal generic function to call that constructor.

C# static member "inheritance" - why does this exist at all?

In C#, a superclass's static members are "inherited" into the subclasses scope. For instance:
class A { public static int M() { return 1; } }
class B : A {}
class C : A { public new static int M() { return 2; } }
[...]
A.M(); //returns 1
B.M(); //returns 1 - this is equivalent to A.M()
C.M(); //returns 2 - this is not equivalent to A.M()
Now, you can't inherit static classes, and the only place I can imagine that static inheritance might matter ignores it entirely: although you can make a generic constraint that requires a type parameter T to be a subclass of A, you still cannot call T.M() (which probably simplifies things for the VM), let alone write a different M implementation in a subclass and use that.
So, the "inheritance" of static members merely looks like namespace pollution; even if you explicitly qualify the name (i.e. B.M) A's version is still resolved.
Edit compare with namespaces:
namespace N1{ class X(); }
namespace N1.N2 { class X(); }
namespace N1.N2.N3 { [...] }
Within N1.N2.N3 It makes sense that if I use X without qualification it refers to N1.N2.X. But if I explicitly refer to N1.N2.N3.X - and no such class exists - I don't expect it to find N2's version; and indeed to compiler reports an error if you try this. By contrast, if I explicitly refer to B.M(), why doesn't the compiler report an error? After all, there's no "M" method in "B"...
What purpose does this inheritance have? Can this feature be used constructively somehow?
So, the "inheritance" of static
members merely looks like namespace
pollution
That's right, except that one guy's pollution is another guy's added spicy flavouring.
I think Martin Fowler, in his work on DSLs, has suggested using inheritance in this way to allow convenient access to static methods, allowing those methods to be used without class name qualification. So the calling code has to be in a class that inherits the class in which the methods are defined. (I think it's a rotten idea.)
In my opinion, static members should not be mixed into a class with a non-static purpose, and the issue you raise here is part of the reason why it's important not to mix them.
Hiding private static mutable data inside the implementation of an otherwise "instancey" class is particularly horrible. But then there are static methods, which are even worse mixers. Here's a typical use of static methods mixed into a class:
public class Thing
{
// typical per-instance stuff
int _member1;
protected virtual void Foo() { ... }
public void Bar() { ... }
// factory method
public static Thing Make()
{
return new Thing();
}
}
It's the static factory method pattern. It's pointless most of the time, but even worse is that now we have this:
public class AnotherThing : Thing { }
This now has a static Make method which returns a Thing, not a AnotherThing.
This kind of mismatch strongly implies that anything with static methods should be sealed. Static members fail to integrate well with inheritance. It makes no sense to have them heritable. So I keep static things in separate static classes, and I gripe about redundantly having to declare every member static when I've already said that the class is static.
But it's just one of those too-late-now things. All real, working languages (and libraries, and products) have a few of them. C# has remarkably few.
I rather have access to all my based static members in derived classes.
Otherwise i would need to know exactly where the static member was defined and call it explicitly.
When using Intellisense you can automatically know every static member available to that kind of class.
Of course, they are not inherited, it's just a shortcut
That's how it works, would probably just be a stupid answer in most cases. But in this case, it is how it works; since you derive from A you say that you are A + the extra features you add.
Therefore you need to be able to access the same variables that you would through an instance of A.
However, inheriting a static class makes no sense while access to the static members / fields / methods does.
An example of this is the following:
internal class BaseUser
{
public static string DefaultUserPool { get; set; }
}
internal class User : BaseUser
{
public int Id { get; set; }
public string Name { get; set; }
public User Parent { get; set; }
}
Where the test looks like this:
User.DefaultUserPool = "Test";
BaseUser.DefaultUserPool = "Second Test";
Console.WriteLine(User.DefaultUserPool);
Console.WriteLine(BaseUser.DefaultUserPool);
Both of the WriteLines outputs "Second Test", this is because both BaseUser and User should use DefaultUserPool, by design. And overriding static implemented methods wouldn't make mucn sense since it's just an accessor in the child-class.
There can be only one. Overriding it would mean that there's a new implementation for that sub-class, which would kill the term "static".
Actually, as I understand it, this is just a shortcut provided by the compiler. Syntax sugar. B.M() will just compile to A.M() since B does not have a static M() and A does. It's for easier writing, nothing else. There is no "static inheritance".
Added: And the requirement for new when "redefining" is just so that you don't accidentally shoot yourself in the foot.
I think it's for accessing protected static members of the base class.
class Base
{
protected static void Helper(string s)
{
Console.WriteLine(s);
}
}
class Subclass : Base
{
public void Run()
{
Helper("From the subclass");
}
}
So... What's the alternative?
The question mentions...
why doesn't the compiler report an error? After all, there's no "M" method in "B"...
But there is a derived "M" method in "B" class.
If the compiler did not present the programmer a unified virtual table for base cases, then the programmer would have to go hunting through base types to find static methods. This would break polymorphism.
Wikipedia...
Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability of one type, A, to appear as and be used like another type, B....
In strongly typed languages, polymorphism usually means that type A somehow derives from type B, or type C implements an interface that represents type B.
I always see it a means of preventing any form of polymorphism by the inheriting class on those items that you wish to retain the same function for all child classes.
ignore the above for some reason I was thinking of sealed instead of static
I suppose that you'd use static member variables and functions in order to ensure that any data or functionallity is not dependent on the a class instance as it would be instantiated only the once.
An example of use would be say a counter value that would keep a live count of all instances of a superclass's subclasses (each subclass increments the static count value on construction). This count value would be available and equal for all instances of the subclass.

C#, implement 'static abstract' like methods

I recently ran into a problem where it seems I need a 'static abstract' method. I know why it is impossible, but how can I work around this limitation?
For example I have an abstract class which has a description string. Since this string is common for all instances, it is marked as static, but I want to require that all classes derived from this class provide their own Description property so I marked it as abstract:
abstract class AbstractBase
{
...
public static abstract string Description{get;}
...
}
It won't compile of course. I thought of using interfaces but interfaces may not contain static method signatures.
Should I make it simply non-static, and always get an instance to get that class specific information?
Any ideas?
You can't.
The place to do this is with Attributes.
Eg
[Name("FooClass")]
class Foo
{
}
If you don't mind deferring to implementations to sensibly implement the Description property, you can simply do
public abstract string ClassDescription {get; }
// ClassDescription is more intention-revealing than Description
And implementing classes would do something like this:
static string classDescription="My Description for this class";
override string ClassDescription { get { return classDescription; } }
Then, your classes are required to follow the contract of having a description, but you leave it to them to do it sensibly. There's no way of specifying an implementation in an object-oriented fashion (except through cruel, fragile hacks).
However, in my mind this Description is class metadata, so I would prefer to use the attribute mechanism as others have described. If you are particularly worried about multiple uses of reflection, create an object which reflects over the attribute that you're concerned with, and store a dictionary between the Type and the Description. That will minimize the reflection (other than run time type inspection, which isn't all that bad). The dictionary can be stored as a member of whatever class that typically needs this information, or, if clients across the domain require it, via a singleton or context object.
If it is static, there is only one instance of the variable, I don't see how inheritance would make sense if we could do what you want to accomplish with static vars in derived classes. Personally I think you are going to far to try to avoid a instance var.
Why not just the classic way?
abstract class AbstractBase
{
protected string _Description = "I am boring abstract default value";
}
class Foo : AbstractBase {
public Foo() {
_Description = "I am foo!";
}
}
Combining static and abstract is somewhat meaningless, yes. The idea behind static is one need not present an instance of the class in order to use the member in question; however with abstract, one expects an instance to be of a derived class that provides a concrete implementation.
I can see why you'd want this sort of combination, but the fact is the only effect would be to deny the implementation use of 'this' or any non-static members. That is, the parent class would dictate a restriction in the implementation of the derived class, even though there's no underlying difference between calling an abstract or 'static abstract' member (as both would need a concrete instance to figure out what implementation to use)
A possible workaround is to define a Singleton of your derived class in your base class with the help of Generics.
import System;
public abstract class AbstractBase<T>
where T : AbstractBase<T>, new()
{
private static T _instance = new T();
public abstract string Description { get; }
public static string GetDescription()
{
return _instance.Description;
}
}
public class DerivedClass : AbstractBase<DerivedClass>
{
public override string Description => "This is the derived Class";
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DerivedClass.GetDescription());
Console.ReadKey();
}
}
The trick is to tell your AbstractBase<T> some details about how DerivedClass is implemented:
It is newable with where T: new() so it can create a Singleton instance
It derives from itself with where T : AbstractBase<T> so it knows that there will be a implementation of Description
This way _instance contains the Description field which can be called in the static Method GetDescription().
This forces you to overwrite Descriptionin your DerivedClass and allows you to call its value with DerivedClass.GetDescription()
It's not static if it has to be called on an instance.
If you're not calling it on an instance, then there's no polymorphism at play (i.e. ChildA.Description is completely unrelated to ChildB.Description as far as the language is concerned).
You can...
In the abstract class...
protected abstract InWindow WindowInstance { get; set; }
In the derived class...
private static InWindow _instance;
protected override InWindow WindowInstance
{
get => _instance;
set => _instance = value;
}
You could make the "abstract" base method throw an Exception, so then a developer is "warned" if he tries to invoke this method on a child class without overriding.
The downside is that one might extend the class and not use this method. Then refer to other answers provided.

Categories