I have a generic method that takes a request and provides a response.
public Tres DoSomething<Tres, Treq>(Tres response, Treq request)
{/*stuff*/}
But I don't always want a response for my request, and I don't always want to feed request data to get a response. I also don't want to have to copy and paste methods in their entirety to make minor changes. What I want, is to be able to do this:
public Tre DoSomething<Tres>(Tres response)
{
return DoSomething<Tres, void>(response, null);
}
Is this feasible in some manner? It seems that specifically using void doesn't work, but I'm hoping to find something analogous.
You cannot use void, but you can use object: it is a little inconvenience because your would-be-void functions need to return null, but if it unifies your code, it should be a small price to pay.
This inability to use void as a return type is at least partially responsible for a split between the Func<...> and Action<...> families of generic delegates: had it been possible to return void, all Action<X,Y,Z> would become simply Func<X,Y,Z,void>. Unfortunately, this is not possible.
No, unfortunately not. If void were a "real" type (like unit in F#, for example) life would be a lot simpler in many ways. In particular, we wouldn't need both the Func<T> and Action<T> families - there'd just be Func<void> instead of Action, Func<T, void> instead of Action<T> etc.
It would also make async simpler - there'd be no need for the non-generic Task type at all - we'd just have Task<void>.
Unfortunately, that's not the way the C# or .NET type systems work...
Here is what you can do. As #JohnSkeet said there is no unit type in C#, so make it yourself!
public sealed class ThankYou {
private ThankYou() { }
private readonly static ThankYou bye = new ThankYou();
public static ThankYou Bye { get { return bye; } }
}
Now you can always use Func<..., ThankYou> instead of Action<...>
public ThankYou MethodWithNoResult() {
/* do things */
return ThankYou.Bye;
}
Or use something already made by the Rx team: http://msdn.microsoft.com/en-us/library/system.reactive.unit%28v=VS.103%29.aspx
You could simply use Object as others have suggested. Or Int32 which I have seen some use. Using Int32 introduces a "dummy" number (use 0), but at least you can't put any big and exotic object into an Int32 reference (structs are sealed).
You could also write you own "void" type:
public sealed class MyVoid
{
MyVoid()
{
throw new InvalidOperationException("Don't instantiate MyVoid.");
}
}
MyVoid references are allowed (it's not a static class) but can only be null. The instance constructor is private (and if someone tries to call this private constructor through reflection, an exception will be thrown at them).
Since value tuples were introduced (2017, .NET 4.7), it is maybe natural to use the struct ValueTuple (the 0-tuple, the non-generic variant) instead of such a MyVoid. Its instance has a ToString() that returns "()", so it looks like a zero-tuple. As of the current version of C#, you cannot use the tokens () in code to get an instance. You can use default(ValueTuple) or just default (when the type can be inferred from the context) instead.
I like the idea by Aleksey Bykov above, but it could be simplified a bit
public sealed class Nothing {
public static Nothing AtAll { get { return null; } }
}
As I see no apparent reason why Nothing.AtAll could not just give null
The same idea (or the one by Jeppe Stig Nielsen) is also great for usage with typed classes.
E.g. if the type is only used to describe the arguments to a procedure/function passed as an argument to some method, and it itself does not take any arguments.
(You will still need to either make a dummy wrapper or to allow an optional "Nothing". But IMHO the class usage looks nice with myClass<Nothing> )
void myProcWithNoArguments(Nothing Dummy){
myProcWithNoArguments(){
}
or
void myProcWithNoArguments(Nothing Dummy=null){
...
}
void, though a type, is only valid as a return type of a method.
There is no way around this limitation of void.
What I currently do is create custom sealed types with private constructor. This is better than throwing exceptions in the c-tor because you don't have to get until runtime to figure out the situation is incorrect. It is subtly better than returning a static instance because you don't have to allocate even once. It is subtly better than returning static null because it is less verbose on the call side. The only thing the caller can do is give null.
public sealed class Void {
private Void() { }
}
public sealed class None {
private None() { }
}
Related
First let me try to explain my situation.
Since we can not add a string value to an enumeration and I am NOT adding a custom parameter class in order to store and read it (for performance reasons since reflection is involved if I use something like: public class StringValueAttribute : Attribute), so I decided to use the following type of class:
public class Permissions
{
public const string X1 = "X1";
public const string X2 = "X2";
public const string X3 = "X3";
....
public const string X43 = "CAN_HAVE A LONG NAME AND NOT FOLLOWING A PATTERN";
}
Now I want to create a method that will receive a string as a parameter. However, I want to force the programmer to use only strings from the class Permissions.
If I would have used an enumeration, this would not be a problem since the method parameter type is explicity defined.
When we are working with generics we can implement this type of constrains.
Is there anything "LIGHT/FAST" that I am not aware that allows me to do this in my case?
I've been in this situation before many times. I almost always went with the struct approach.
First you define a struct like so:
public struct Permission : IEquatable<Permission>, IEquatable<string>
{
private readonly string key;
private Permission(string key)
{
this.key = key;
}
// implement Equals, GetHashCode, IEquatable...
}
Then you can just declare all the permissions you want to have as static members of the struct.
public class Permission
{
// ...
public static readonly First = new Permission("First");
}
Now, using struct as opposed to class has one major benefit and one major drawback:
Pro: No heap allocation needed, no a pointer dereference. It is as fast as it can be.
Cons: Even though we declared the constructor private structs always have an implicit default constructor. It is invisible but arrays are default initialized with it and is does default(T).
If you decide to go with a struct, it's highly advisable to add the following method/property:
public bool IsEmpty
{
get { return this.key == null; }
}
If you decide on the class approach, the allocation is mostly saved as I don't assume you will be allocating new instances apart of the ones already declared as static members, so the drawback is really the extra pointer.
No, there's nothing that does this within the language. If you can possibly avoid this situation, it would be good to do so. When we have more context, we may be able to suggest alternatives.
If you really have to use this approach, I would suggest first adding execution-time validation to the method, so that if an invalid value is passed in, you'll find out immediately rather than proceeding with invalid data.
Secondly, you could write a Roslyn analyzer to find all invocations of your method, and check that the argument is of the appropriate form. However, that could cause a problem if you have a situation like this:
public void Foo()
{
FooImpl(Permissions.X1);
DoSomethingElse();
}
private void FooImpl(string permission)
{
RealMethodWithChecking(permission);
}
At that point, your Roslyn analyzer would go off because the argument to RealMethodWithChecking doesn't come directly from Permissions - but it's a parameter which itself comes from Permissions. Whether or not this is a problem, and how you decide to address it, will very much depend on context.
I am currently working with .Net 2.0 and have an interface whose generic type is used to define a method's return type. Something like
interface IExecutor<T> {
T Execute() { ... }
}
My problem is that some classes that implement this interface do not really need to return anything.
In Java you can use java.lang.Void for this purpose, but after quite a bit of searching I found no equivalent in C#. More generically, I also did not find a good way around this problem. I tried to find how people would do this with delegates, but found nothing either - which makes me believe that the problem is that I suck at searching :)
So what's the best way to solve this? How would you do it?
Thanks!
You're going to have to either just use Object and return null, create your own object to represent void, or just make a separate interface that returns void.
Here's an idea for the second one:
public class Void
{
public static readonly Void Instance = null; // You don't even need this line
private Void() {}
}
that way someone can't create an instance of the class. But you have something to represent it. I think this might be the most elegant way of doing what you want.
Also, you might want to make the class sealed as well.
Just use Object as the type , and return null.
That means you might need to write an adapter if you need to call a delecate who does in fact have a void return type
Edit: C# 3.0, net 3.5.
I am C++ programmer, so maybe I miss some simple solution in C#.
Simplified example:
I have several classes inherited from class MyBase (with method Inc). The inherited classes may override Inc. I have several overloaded "functions" (static methods) for the inherited classes:
void Print(MyInherited1 i1) ....
void Print(MyInherited2 i2) ....
and so on. Edit: those methods are "external" to the MyBase and MyInherited, they are not part of any of those classes.
I have generics function that modify its argument and call the Print function:
void Transform<T>(T t)
{
t.Inc();
Print(t);
}
Edit: this is simplified example, in real code I cannot convert the Transform method to non-generic one using just polymorphism.
Now, in C++ it would work just like that. However in C# method Inc is unknown. So I specify that T is of type MyBase.
void Transform<T>(T t) where T : MyBase
{
t.Inc();
Print(t);
}
but I still have the problem with Print -- there is no such method for the base class.
As a workaround I used ugly (!) solution -- PrintProxy where I put several
if (t is Inherited1)
Print(t as Inherited1);
else if ...
How to mix those two concepts -- overloading and generics? Nice, C# way?
Thank you in advance for help.
One option in C# 4 is to use dynamic typing:
void Transform<T>(T t)
{
t.Inc();
dynamic d = t;
Print(d);
}
That will perform the overload resolution for you at execution time - which is basically the best you can do unless you can provide a genuinely generic Print method, as there will only be one version of Transform generated.
Note that there's no real need to be generic at this point - you could replace it with:
void Transform(MyBase t)
{
...
}
I typically find that constraints based on interfaces are more useful than those based on classes, unless I'm also doing something else generic (such as creating a List<T> which should be of the right actual type).
Obviously this dynamic approach has downsides:
It requires .NET 4.0
It's slower than a compile-time binding (although it's unlikely to be significant unless you're calling it a heck of a lot)
There's no compile-time validation (you can add an overload which takes object as a sort of fallback to provide custom error handling, but you still have to wait until execution time)
Basically this is just a difference between .NET generics and C++ templating - they're very different creatures, even if they tackle many similar problems.
Rather than having static Print methods, is there any reason you can't write an abstract Print method in MyBase, and override it in each class? That feels like a more OO solution anyway, to be honest - although obviously it doesn't make sense if the printing is actually somewhat logically distant from the class itself. Even if you don't want the actual Print method in the original type hierarchy, might you be able to expose enough functionality to let you write a virtual Print method? I assume all these methods should come up with some similar kind of result, after all.
EDIT: A couple of alternative ideas...
Passing in the printer
You can pass in a delegate to do the printing. If you're calling this from a non-generic context which knows the actual type, you can take advantage of method group conversions to make this simple. Here's a short but complete example:
using System;
class Test
{
static void SampleMethod<T>(T item, Action<T> printer)
{
// You'd do all your normal stuff here
printer(item);
}
static void Print(string x)
{
Console.WriteLine("Here's a string: {0}", x);
}
static void Print(int x)
{
Console.WriteLine("Here's an integer: {0}", x);
}
static void Main()
{
SampleMethod(5, Print);
SampleMethod("hello", Print);
}
}
Use a type/delegate dictionary
Another option is to have a Dictionary<Type, Delegate> containing the printing methods. This could either be inlined (if the printing methods are simple) or something like this:
static readonly Dictionary<Type, Delegate> Printers =
new Dictionary<Type, Delegate>
{
{ typeof(MyClass1), (Action<MyClass1>) Print },
{ typeof(MyClass2), (Action<MyClass2>) Print },
{ typeof(MyClass3), (Action<MyClass3>) Print },
};
Then in your method:
Delegate printer;
if (Printers.TryGetValue(typeof(T), out printer))
{
((Action<T>) printer)(t);
}
else
{
// Error handling
}
This is another execution time solution though, and you'd need a bit more work if you wanted it to handle further derivation (e.g. walking up through the base classes if it can't find the relevant printer).
That's by design. The compiler has to know at compile time what method (overload) to bind to for the unbound (!) generic class, and in your case, this would only be known after the generic type has been set.
In contrast to the C++ templates, generics are working in a different way even though they share a similar syntax.
My first suggestion would be to use an interface instead of generics. I see no point in using generics in this example.
void Transform(IMyBase t)
{
t.Inc();
}
where IMyBase is:
interface IMyBase
{
void Inc();
}
Option A
[Edit] Since Print does not belong to IMyBase, you could separate the printing logic completely and do something like this:
void Transform(IMyBase t, IPrintLogic printLogic)
{
t.Inc();
printLogic.Print(t);
}
where IPrintLogic is defined as:
interface IPrintLogic
{
void Print(IMyBase t);
}
now you have the freedom to instantiate any print logic you want:
MyInherited1 obj = new MyInherited1();
MyPrintLogic printer = new MyPrintLogic();
Transform(obj, printer);
or, use a factory of some sort:
Transform(obj, PrintLogicFactory.Create(obj));
Code inside your factory could then be similar to a bunch of if/then/else blocks, like you have right now.
Option B - Creating an intermediate object (like the Adapter pattern)
Depending on what your Transform method actually does, this may be an option also:
IPrepared Transform(IMyBase t)
{
t.Inc();
return this.PrepareForPrinting(t);
}
and then print the IPrepared object, which is "prepared" for printing in a way:
interface IPrintLogic
{
void Print(IPrepared t);
}
In that case, you would use it like:
MyInherited1 obj = new MyInherited1();
IPrepared prepared = Transform(obj);
MyPrintLogic printer = new MyPrintLogic();
printer.Print(prepared);
why not using an interface?
void Transform<T>(T t) where T : MyBase, IMyPrintableClass
{
t.Inc();
t.Print();
}
What is the access modifier on the .Print(..) method in your MyBase class?
If none is specified it's private by default which would preclude derived classes from accessing it - mark it protected at least.
protected void Print(MyBase obj) {
//do stuff
}
If for some reason Print(..) isn't in the inheritance hierarchy and you're trying to use it in a composited way try public (although your description indicates this isn't the case).
public void Print(MyBase obj) { //...
Public is a good way to debug it because your code is most apt to "see" it whether from the same assembly or a different one.
I have a generic class that I need to constrain to only value types (int, float, etc.). I have a method that calls the Parse method based on a test of the type. For example:
class MyClass<T>
{
...
private static T ParseEntry(string entry)
{
if(typeof(T) == typeof(float))
{
return (T) float.Parse(entry);
}
if(typeof(T) == typeof(int))
{
.... you get the idea
}
}
}
Constraining T to struct doesn't work and I really want to avoid boxing/unboxing if possible. Any ideas?
EDIT: To give a little more insight into this. I noticed in a library I'm developing that two classes had very similar properties/methods etc. the only difference was the underlying type of data (int or float). THis lead me to a design with generics. The only hangup is because of the call to the specific Parse method depending on if it's a float or int. I could get around it with boxing/unboxing but I really wanted to avoid that if possible.
private static T ParseEntry(string entry)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
return (T) conv.ConvertFromString(entry);
}
which has the advantage of working with any type with a type-converter (or you can add your own at runtime). It does have boxing, but really, it isn't so bad. If that is your biggest problem, then you're going about this the wrong way.
Unfortunately, you cannot create constraints of the type of describe. You cannot write, for example:
class MyClass<T> where T : int { ... } // won't compile
You may be better off leaving the constraint to be struct, but add some runtime checks to make sure that T is only one of the supported types when you instantiate the class. Since you haven't said much how you're planning to use your class - it's hard to offer alternative design advice on how to achieve better type safety.
EDIT: You should look at the type converter option that Marc and others recommend. This seems like the way to go.
EDIT: One possible idea that occurs to me, is to make the Parse() method actually be a delegate: Func<string,T> - that you assign during construction. This would make it possible for you to:
Avoid the inefficient and awkward if/else logic.
Improve the future use of your class to other value types (structs, BigDecimal, etc)
Here's a code example of what I mean:
class MyClass<T>
{
private readonly Func<string,T> ParseEntry;
public MyClass( Func<string,T> parser )
{
ParseEntry = parser;
}
}
public static class AvailableParsers
{
public static Func<string,int> ParseInt = s => int.Parse( s );
public static Func<string,float> ParseFloat = s => float.Parse(s);
}
You can read about the available constraints here. The only constraints available are:
struct (optional)
new() (optional)
interface constraint (optional, multiple allows)
base class constraint (optional, only one allowed)
naked constraints ( such as where T : TResult )
Stupid maybe, but - if you are talking about a limited set of types, why don't you just overload the method? Like the *Writer.Write() methods, that have overloads for every "base" type?
In short: Why generic, if you do different things based on the type anyway (that somehow defeats the purpose of doing the same thing for whatever type is passed in)?
Edit: Thinking about the usage I think you might actually want to use Convert.ChangeType.
Something like this:
class MyClass<T> where T: IConvertible
{
private static T ParseEntry(string entry)
{
return (T)Convert.ChangeType(entry, typeof(T));
}
}
I guess I don't see the value here... why not use the Convert class?
Like Mr. Bushkin said, you can't do that. So you're other option would be to simply make several overloads of the method for each primitive type.
Also, imagine that you didn't have to deal with primitive types, but you really wanted to handle all structs - it still wouldn't be possible, since the struct is not guaranteed to implement an (heretofore imaginary) interface called IParsable to be cast into T.
For example I now created a this tiny class:
public static class FileSystemInfoComparers<T> where T : FileSystemInfo
{
public static IEqualityComparer<T> FullName
{
get { return new FullNameComparer(); }
}
private class FullNameComparer : IEqualityComparer<T>
{
public bool Equals(T x, T y) { return x.FullName == y.FullName; }
public int GetHashCode(T obj) { return obj.FullName.GetHashCode(); }
}
}
I would like it if I could just do
var comparer = FileSystemInfoComparers.FullName;
and have an instance of IEqualityComparer<FileSystemInfo>, since I didn't specify any type and FileSystemInfo is the most generic type T can be. With no type constraint the default type could for example be object or something.
Maybe not the best example, but anyways just got curious here :p
Sounds like a recipe for trouble to me.
In particular, you could easily create a non-generic class called FileSystemInfoComparers with a static property of the same name, and suddenly your code would mean something completely different.
I'd rather keep things simple. (Generics are complicated enough already, and type inference in particular is pretty hairy.)
That is an interesting idea and it could definitely work but consider that it would only work in cases where the generic type argument is constrained with a concrete type.
The .NET compilers are very good at type inference but tend to shy away from making any assumptions. I don't see any reason why this couldn't be done except that it would only work in a small number of highly-specific instances. Since it has no general purpose I would imagine that Microsoft would be less inclined to make a change to support it.
You could possible do this by having a helper class that has the default type you want set. But what you are asking for currently cannot be done in C# 3.0.