Reputation: 3
I'm getting a compile-time type conversion error with this code... dunno if i'm just tired, but I can't figure out what I need to change in the class to fix this. Any pointers would be awesome, thanks
The error is: "error CS0266: Cannot implicitly convert type
csharpfinal.Packaging<string>
tocsharpfinal.IGetValue<object>
. An explicit conversion exists (are you missing a cast?)"
interface ISetValue<T>
{
void SetData(T data);
}
interface IGetValue<T>
{
T GetData();
}
class Packaging<T> : ISetValue<T>, IGetValue<T>
{
private T storedData;
void ISetValue<T>.SetData(T data)
{
this.storedData = data;
}
T IGetValue<T>.GetData()
{
return this.storedData;
}
}
class Program
{
static void Main(string[] args)
{
Packaging<string> stringPackage = new Packaging<string>();
ISetValue<string> setStringValue = stringPackage;
setStringValue.SetData("Sample string");
// the line below causes a compile-time error
IGetValue<object> getObjectValue = stringPackage;
Console.WriteLine("{0}", getObjectValue.GetData());
}
}
Upvotes: 0
Views: 176
Reputation: 1001
Packaging<string> stringPackage = new Packaging<string>();
^ generic type is string
IGetValue<object> getObjectValue = stringPackage;
but you are trying to cast an object
generic to a string
generic, that's why you get the compile-time error.
You can change the generic type of your object initialization to object
to fix it:
Packaging<object> stringPackage = new Packaging<object>();
ISetValue<object> setStringValue = stringPackage;
Upvotes: 0
Reputation: 1967
Modify this code
interface ISetValue<T>
{
void SetData(T data);
}
interface IGetValue<T>
{
T GetData();
}
to
interface ISetValue<in T>
{
void SetData(T data);
}
interface IGetValue<out T>
{
T GetData();
}
For generic type parameters, the out keyword specifies that the type parameter is covariant. You can use the out keyword in generic interfaces and delegates.
Covariance enables you to use a more derived type than that specified by the generic parameter. This allows for implicit conversion of classes that implement variant interfaces and implicit conversion of delegate types. Covariance and contravariance are supported for reference types, but they are not supported for value types.
Upvotes: 2
Reputation: 17485
interface ISetValue<in T>
{
void SetData(T data);
}
interface IGetValue<out T>
{
T GetData();
}
class Packaging<T> : ISetValue<T>, IGetValue<T>
{
private T storedData;
void ISetValue<T>.SetData(T data)
{
this.storedData = data;
}
T IGetValue<T>.GetData()
{
return this.storedData;
}
}
class Program
{
static void Main(string[] args)
{
Packaging<string> stringPackage = new Packaging<string>();
ISetValue<string> setStringValue = stringPackage;
setStringValue.SetData("Sample string");
// the line below causes a compile-time error
IGetValue<object> getObjectValue = stringPackage;
Console.WriteLine("{0}", getObjectValue.GetData());
}
}
more info :http://msdn.microsoft.com/en-us/library/dd469487.aspx
Upvotes: 0