.Net: Unable to Cast Object to Interface It Implements

Unable to cast object to interface it implements - cast interface to another interface

If you post your question correctly, it works fine:

class Program
{
static void Main()
{
Call(new Car());

Call(new MotorBike());
}

public static void Call(IVehicles vehicle)
{
Object someIrrelevantObject = vehicle.SomeValue;
//here my change begins
IPersonalVehicles personalVehicle = (IPersonalVehicles)vehicle;
long somePersonalValue = personalVehicle.SomePersonalValue;
}

}

public interface IVehicles

{
Object SomeValue { get; }
}

public interface IPersonalVehicles

{
long SomePersonalValue { get; }
}

public class Car : IVehicles, IPersonalVehicles
{
public long SomePersonalValue => long.MinValue;

public object SomeValue => "car value";
}

public class MotorBike : IVehicles, IPersonalVehicles
{
public long SomePersonalValue => long.MaxValue;

public object SomeValue => "motorbike value";
}

Why I cannot cast an object to an interface it is implementing?

I think you should take a look at my response to this question, it explains you case Interface with generic object of the interface type

By the way I suggest you make changes to you GetIt Function like that :

public static IASet<T> GetIt<T>() 
where T : IItem
{
ASet a = new ASet();
a.Collection = new HashSet<OneItem>();
a.Collection.Add(new OneItem() { Name = "one" });
a.Collection.Add(new OneItem() { Name = "two" });
//for test :
foreach (var i in a.Collection)
{
Console.WriteLine(i.Name);
}

/*Error 1 Cannot implicitly convert type 'ConsoleApplication2.Program.ASet'
* to 'ConsoleApplication2.IASet<ConsoleApplication2.IItem>'. An explicit
* conversion exists (are you missing a cast?)
*/
//return a;

/*Unable to cast object of type 'ASet' to type
* 'ConsoleApplication2.IASet`1[ConsoleApplication2.IItem]'.
*/
return (IASet<T>)a;
}

and then you need to call it like that:

  IASet<OneItem> aset = GetIt<OneItem>();
foreach (IItem i in aset.Collection)
Console.WriteLine(i.Name);

if you want more details you have to explain your requirement more.

C# - Error casting object to interface

Shared projects compile their source files directly into each project that references them.

Therefore, you have two ICrawler interfaces, one in each assembly, which are not the same type (even though they're identical).

You're trying to cast the new instance to the copy of the interface that it doesn't implement; you can't do that.

You should use a normal Class Library, not a Shared Project.

Unable to cast object of generic type to generic interface C#

That's a lot of levels of indirection you got there...

Here's the issue:

public abstract class Rule<TDmModel, TMiddle, TDb> : IRule<TDmModel, TDb>
where TDmModel : IDmModel
where TDb : IDbModel

public class RuleA : Rule<DmModel, Middle, DbMode>
public class RuleB : RuleA
...
var ruleB = (IRule<IDmModel, IDbModel>)new RuleB();

RuleB implements IRule<DmModel, DbMode>

This cannot be cast to IRule<IDmModel, IDbModel>. C# does not support this type of casting. For the same reason, you cannot do List<object> b = (List<object>)new List<string>(); (Gives "Cannot convert type 'System.Collections.Generic.List<string> to System.Collections.Generic.List<object>.")

This is an issue with covariance.

Here is some more information from Microsoft on the subject: https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance

Unable to cast 2 objects although they share same interface

You can use json for this. We do this all the time to cast DataTable into a model.

You Serialize the first model and Deserialize it into the other one.
Doing it this way, only the fields that are in common are touched.

        var deserializeSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace };
string serializedObject = JsonConvert.SerializeObject(A, deserializeSettings);
B b = JsonConvert.DeserializeObject<B>(serializedObject);

Unable to cast C#

Casting doesn't work that way. When casting (an object statically known as) object to another type, it must already be an instance of that type for it to work. Maybe you'd like to convert from one to the other with AutoMapper, e.g.

Mapper.CreateMap<MyClass1, MyClass2>();

// later...
MyClass2 temp = Mapper.Map<MyClass2>(myObjectInput);

Or manually copy the properties, maybe in a constructor:

public MyClass2(MyClass1 other)
{
this.SomeProperty = other.SomeProperty;
// etc
}

MyClass2 temp = new MyClass2((MyClass1)myObjectInput);

More likely, what you should do is make the projects share MyClass in a way that .NET understands and supports natively: by putting it in a project that can be referenced by both projects. If one project should reference the other, do that; otherwise, create a third project as a library.

C# - Casting an object to an interface

If you are sure that:

  1. canvas.Children[0] returns a CustomIsocelesTriangle.

    Use the debugger to verify, or print the type to the console:

    var shape = canvas.Children[0];
    Console.WriteLine(shape.GetType());
    // Should print "program_4.CustomIsocelesTriangle"
  2. You're casting to ICustomShape (not CustomShape).

  3. CustomIsocelesTriangle implements ICustomShape.

    Try this to verify (it should compile):

    ICustomShape shape = new CustomIsocelesTriangle(/* Fake arguments */);

Then perhaps:

  • you have CustomIsocelesTriangle in a different project or assembly, and you forgot to save and rebuild it after you made it implement ICustomShape;
  • or, you reference an older version of the assembly;
  • or, you have two interfaces named ICustomShape or two classes CustomIsocelesTriangle (perhaps in different namespaces), and you (or the compiler) got them mixed up.


Related Topics



Leave a reply



Submit