Generic Type Conflicts? - c#

I saw this interesting question which talks about T declaration at the class level and the same letter T ( different meaning) at the method level.
So I did a test.
static void Main(string[] args)
{
var c = new MyClass<int>(); //T is int
c.MyField = 1;
c.MyProp = 1;
c.MyMethod("2");
}
public class MyClass<T>
{
public T MyField;
public T MyProp { get; set; }
public void MyMethod<T>(T k)
{
}
}
As Eric said , the compiler does warn.
But Hey , what happened to type safety ? I assume there is a type safety at the Method level but what about the global context of the class where T already has been declared.
I mean if someone would have asked me , I would guess there should be an error there and not a warning.
Why the compiler allows that? ( I would love to hear a reasonable answer)

Interesting question. Type safety is preserved here. Behaviour is alike global and local variables. In MyMethod type T is unambiguous. We can also create and return new instance of MyClass as follows:
public class MyClass<T>
{
public T MyField;
public T MyProp { get; set; }
public MyClass<T> MyMethod<T>(T k)
{
return new MyClass<T>();
}
}
The program:
static void Main()
{
var c = new MyClass<int>(); //T is int
c.MyField = 1;
c.MyProp = 1;
var myClass = c.MyMethod("2");
myClass.MyField = "2";
myClass.MyField = "4";
}
There is no compilation error and it shouldn't be, because type safety is preserved. Program can be compiled. There is no ambiguity.
The warning should be there, because T overrides its class level counterpart and there is no simple way in MyMethod to obtain that global T. It also obscures legibility.
MSDN says about flexibility and good practice in Generic Methods (C# Programming Guide):
If you define a generic method that takes the same type parameters as the containing class, the compiler generates warning CS0693 because within the method scope, the argument supplied for the inner T hides the argument supplied for the outer T. If you require the flexibility of calling a generic class method with type arguments other than the ones provided when the class was instantiated, consider providing another identifier for the type parameter of the method.

This is not a type-safety issue. It is only a readability issue - that's why it's just a warning. (Also, T hides the outer T.)
If change MyMethod() to:
public void MyMethod<T>(T k)
{
Console.WriteLine(typeof(T).FullName);
}
It'll print out System.String for your sample code, proving that it is getting the correct type.

Related

Passing generic into a class constructor list

I have a class that takes a generic as a parameter like this
public MyNewClass(string text, T myClass, int f, bool test = false)
The compiler is complaining about T myClass.
I know I can pass "defined" generic classes to a class constructor (such as List, Dictionary etc) and have seen that this can be done in C# as well, but can't find a reference to it.
You should declare the generic parameter, when you declare your class.
public class MyNewClass<T>
{
}
Then this parameter could be accessible from any of the class's methods. When you will create an instance of your MyNewClass, you should define also the type of T, for instance:
var instanceOfMyNewClass = new MyNewClass<className>(text, classIntance, f, true);
where classInstance is an instance of an object of type className.
A good introduction about generics is here.
I suspect that the issue you are facing is that the following does not compile
public class Foo<T>
{
public Foo(string s, T t) { }
}
var foo = new Foo("Hello", new Something());
The fix to this is to specify in the constructor.
var foo = new Foo<Something>("Hello", new Something());
However, this still seems a little strange given that normally, the C# compiler can infer the type of T.
The problem here is that the C# compiler is only allowed to infer generics on the first parameter of a method. So the following IS allowed.
public class Foo<T>
{
public Foo(T t, string s) { }
}
var foo = new Foo(new Something(), "Hello");

Why do C# out generic type parameters violate covariance?

I'm unclear as to why the following code snippet isn't covarient?
public interface IResourceColl<out T> : IEnumerable<T> where T : IResource {
int Count { get; }
T this[int index] { get; }
bool TryGetValue( string SUID, out T obj ); // Error here?
}
Error 1 Invalid variance: The type parameter 'T' must be invariantly
valid on 'IResourceColl.TryGetValue(string, out T)'. 'T' is
covariant.
My interface only uses the template parameter in output positions. I could easily refactor this code to something like
public interface IResourceColl<out T> : IEnumerable<T> where T : class, IResource {
int Count { get; }
T this[int index] { get; }
T TryGetValue( string SUID ); // return null if not found
}
but I'm trying to understand if my original code actually violates covariance or if this is a compiler or .NET limitation of covariance.
The problem is indeed here:
bool TryGetValue( string SUID, out T obj ); // Error here?
You marked obj as out parameter, that still means though that you are passing in obj so it cannot be covariant, since you both pass in an instance of type T as well as return it.
Edit:
Eric Lippert says it better than anyone I refer to his answer to "ref and out parameters in C# and cannot be marked as variant" and quote him in regards to out parameters:
Should it be legal to make T marked as "out"? Unfortunately no. "out"
actually is not different than "ref" behind the scenes. The only
difference between "out" and "ref" is that the compiler forbids
reading from an out parameter before it is assigned by the callee, and
that the compiler requires assignment before the callee returns
normally. Someone who wrote an implementation of this interface in a
.NET language other than C# would be able to read from the item before
it was initialized, and therefore it could be used as an input. We
therefore forbid marking T as "out" in this case. That's regrettable,
but nothing we can do about it; we have to obey the type safety rules
of the CLR.
Here's the possible workaround using extension method. Not necessarily convenient from the implementor point of view, but user should be happy:
public interface IExample<out T>
{
T TryGetByName(string name, out bool success);
}
public static class HelperClass
{
public static bool TryGetByName<T>(this IExample<T> #this, string name, out T child)
{
bool success;
child = #this.TryGetByName(name, out success);
return success;
}
}
public interface IAnimal { };
public interface IFish : IAnimal { };
public class XavierTheFish : IFish { };
public class Aquarium : IExample<IFish>
{
public IFish TryGetByName(string name, out bool success)
{
if (name == "Xavier")
{
success = true;
return new XavierTheFish();
}
else
{
success = false;
return null;
}
}
}
public static class Test
{
public static void Main()
{
var aquarium = new Aquarium();
IAnimal child;
if (aquarium.TryGetByName("Xavier", out child))
{
Console.WriteLine(child);
}
}
}
It violates covariance because the value provided to output parameters must be of exactly the same type as the output parameter declaration. For instance, assuming T was a string, covariance would imply that it would be ok to do
var someIResourceColl = new someIResourceCollClass<String>();
Object k;
someIResourceColl.TryGetValue("Foo", out k); // This will break because k is an Object, not a String
Examine this little example and you will understand why it is not allowed:
public void Test()
{
string s = "Hello";
Foo(out s);
}
public void Foo(out string s) //s is passed with "Hello" even if not usable
{
s = "Bye";
}
out means that s must be definitely assigned before execution leaves the method and conversely you can not use s until it is definitely assigned in the method body. This seems to be compatible with covariance rules. But nothing stops you from assigning s at the call site before calling the method. This value is passed to the method which means that even if it is not usable you are effectively passing in a parameter of a defined type to the method which goes against the rules of covariance which state that the generic type can only be used as the return type of a method.

Generate Generic Type At Runtime

I am wondering if it is possible to use the type of one variable to set as the type of another generic variable?
For example, say I have this code:
public class Foo: IBar<ushort>
{
public FooBar()
{
Value = 0;
}
public ushort Value { get; private set; }
}
I also have this class:
public class FooDTO<TType> : IBar<TType>
{
public TType Value { get; private set; }
}
In these examples, in the interface for IBar has the property
TType Value;
Then in my code I have this
var myFoo = new Foo();
var fooDataType = myFoo.Value.GetType();
//I know this line of code does not compile, but this is what I am looking to be able to do
var myFooDTO= new FooDTO<fooDataType>();
Is what I am looking for possible? Would it be too slow for high use code (because of using reflection.
You can do this via Reflection, by using Type.MakeGenericType.
This will have some overhead due to reflection, so you'd need to profile it to see if that will be an issue for you.
Why not use Method type inference:
public class FooDTO<TType> {
public TType Value { get; private set; }
}
public class Foo : FooDTO<ushort> { }
static FooDTO<T> GetTypedFoo<T>(T Obj) {
return new FooDTO<T>();
}
static void Main(string[] args) {
Foo F = new Foo();
var fooDTO = GetTypedFoo(F.Value);
}
Always when I read "generic" and "runtime" in one sentence, I always thing "bad design" or "doesnt understant what generic means". Possibly both.
Generic parameter is integral part of the type. So saying "Generate Generic Type At Runtime" is same as "Generate Foo class at runtime". You are either looking for reflection or change design of your algorithm.
Also var keyword is not going to help you in this case. Forget about it.
You're looking for compile-time reflection, a feature that C# doesn't have. So if you're looking for performance optimizations, the solutions are worse than the problem.
D does have this feature, though; you can easily write
int x = 0;
typeof(x) y = x + 2;
or even much more complicated expressions in D, and it's all evaluated at compile-time.
The core of what you want is:
var type = typeof(FooDTO<>).MakeGenericType(fooDataType);
object obj = Activator.CreateInstance(type);
however, you'll notice that this is reflection, and pretty much ties you to object. The usual workaround to this is to have access to a non-generic version of the API, so that you can work with object - for example (with the addition of a non-generic IBar):
IBar bar = (IBar)Activator.CreateInstance(type);
You can of course move the runtime/generics hit higher up - perhaps into a generic method; then everything in the generic method can use T, and you can use MakeGenericMethod to execute that method in the context of a particular T known only at runtime.

extension methods with generics - when does caller need to include type parameters?

Is there a rule for knowing when one has to pass the generic type parameters in the client code when calling an extension method?
So for example in the Program class why can I (a) not pass type parameters for top.AddNode(node), but where as later for the (b) top.AddRelationship line I have to pass them?
class Program
{
static void Main(string[] args)
{
// Create Graph
var top = new TopologyImp<string>();
// Add Node
var node = new StringNode();
node.Name = "asdf";
var node2 = new StringNode();
node2.Name = "test child";
top.AddNode(node);
top.AddNode(node2);
top.AddRelationship<string, RelationshipsImp>(node,node2); // *** HERE ***
}
}
public static class TopologyExtns
{
public static void AddNode<T>(this ITopology<T> topIf, INode<T> node)
{
topIf.Nodes.Add(node.Key, node);
}
public static INode<T> FindNode<T>(this ITopology<T> topIf, T searchKey)
{
return topIf.Nodes[searchKey];
}
public static void AddRelationship<T,R>(this ITopology<T> topIf, INode<T> parentNode, INode<T> childNode)
where R : IRelationship<T>, new()
{
var rel = new R();
rel.Child = childNode;
rel.Parent = parentNode;
}
}
public class TopologyImp<T> : ITopology<T>
{
public Dictionary<T, INode<T>> Nodes { get; set; }
public TopologyImp()
{
Nodes = new Dictionary<T, INode<T>>();
}
}
With respect to the second example, the compiler does not know what type you want for R; it only knows that it must implement IRelationship<T> and have a public default constructor. It can't infer it from any of the parameters you pass to the method because they are of type T. In that case, you need to tell it what class you want to be used for R. If you were to pass in, instead of create an instance of R, as an argument, it would be able to infer the type and you wouldn't need to supply them.
In the first case, you don't need to supply the types because the arguments are of the type and thus the compiler can infer the types that you mean.
Generally, you don't have to explicitly specify the type. You need it when the type is in fact an argument - and example to this is the linq function .Cast - it's type tells it what to do: Cast<Employee>()
In your case this is quite simple: AddRelationship<T,R> has three argumenta, all of type T - how can R be inferred?
I haven't done this particular setup, but my understanding of type inference is that the caller would not need to specify the type. this ITopology<T> topIf will refer to an instance in which the type is already declared. The extension method should pick up the same type parameter implicitly.
A lot of the LINQ extension methods are based on generic extension methods of IEnumerable. It's the same pattern that you're using. That's a good place to start looking.
And as always, test.
I think it is because you do not include any argument with type R in the function.

Passing Delegate object to method with Func<> parameter

I have a method Foo4 that accepts a parameter of the type Func<>. If I pass a parameter of anonymous type , I get no error. But if I create and pass an object of the type 'delegate' that references to a Method with correct signature, I get compiler error. I am not able to understand why I am getting error in this case.
class Learn6
{
delegate string Mydelegate(int a);
public void Start()
{
Mydelegate objMydelegate = new Mydelegate(Foo1);
//No Error
Foo4(delegate(int s) { return s.ToString(); });
//This line gives compiler error.
Foo4(objMydelegate);
}
public string Foo1(int a) { return a.ToString();}
public void Foo4(Func<int, string> F) { Console.WriteLine(F(42)); }
}
It works if you pass a reference to the method directly:
Foo4(Foo1);
This is because actual delegates with the same shape are not inherently considered compatible. If the contracts are implicit, the compiler infers the contract and matches them up. If they are explicit (e.g. declared types) no inference is performed - they are simply different types.
It is similar to:
public class Foo
{
public string Property {get;set;}
}
public class Bar
{
public string Property {get;set;}
}
We can see the two classes have the same signature and are "compatible", but the compiler sees them as two different types, and nothing more.
Because Func<int, string> and MyDelegate are different declared types. They happen to be compatible with the same set of methods; but there is no implicit conversion between them.
//This line gives compiler error.
Foo4(objMydelegate);
//This works ok.
Foo4(objMydelegate.Invoke);
depends on the scenario, but in the general case there's no reason to keep around the Mydelegate type, just use Func<int, string> everywhere :)

Categories

Resources