assume you have a class which has methods using T. And you also have standard methods of the same name.
What happens if T is of the same type as the standard method? The standard method is called.
Is there any way to force him to call the T-method anyway?
using System;
namespace ConsoleApplication3
{
class Program
{
static void Main()
{
Generics<Int32> anInt = new Generics<Int32>(4);
Generics<String> aString = new Generics<String>("test");
}
}
public class Generics<T>
{
public T Member;
public String ErrorMessage;
public Generics(T member)
{
this.Member = member;
}
public Generics(String errorMessage)
{
this.ErrorMessage = errorMessage;
}
}
}
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
A generic type is a class or interface that is parameterized over types, meaning that a type can be assigned by performing generic type invocation, which will replace the generic type with the assigned concrete type.
Type safety. Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
Sorry, there is not.
The simplest solution is to use two different method names to indicate the difference in behaviour. Since the method names in question are constructors, you have no control over the names, so you must change at least one of them into a normal method instead. For example:
public class Generics<T>
{
public T Member;
public String ErrorMessage;
public Generics(T member)
{
this.Member = member;
}
private Generics()
{
// empty constructor just to allow the class to create itself internally
}
public static Generics<T> FromError(String errorMessage)
{
return new Generics<T> { ErrorMessage = errorMessage };
}
}
Personally I would change both constructors to be static methods, so that the difference in behaviour is made absolutely clear to the user. However, if you only change one constructor, make it the error one.
Okay, I'll make my comment into an answer.
First of all, DO NOT do this. DO NOT. You want humans to be able to read your code, not just computers. (There, I've done my duty as a member of the C# programmer space)
Second.
As described here:
If you design your code so that the compiler cannot tell when it's compiling what type you're calling with, you can force it to use the generic method.
static Generics<T> Test<T> (T parameterToTest) {
return new Generics<T>(parameterToTest);
}
static void Main()
{
Generics<Int32> anInt = Test<Int32>(4);
Generics<String> aString = Test<String>("test");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With