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:
canvas.Children[0]
returns aCustomIsocelesTriangle
.
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"You're casting to
ICustomShape
(notCustomShape
).CustomIsocelesTriangle
implementsICustomShape
.
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 implementICustomShape
; - or, you reference an older version of the assembly;
- or, you have two interfaces named
ICustomShape
or two classesCustomIsocelesTriangle
(perhaps in different namespaces), and you (or the compiler) got them mixed up.
Related Topics
C# Property and Ref Parameter, Why No Sugar
Opening Process and Changing Window Position
C#6.0 String Interpolation Localization
Async Always Waitingforactivation
Convert Object to JSON String in C#
How to Find the Position of a Cursor in a Text Box? C#
What Is the Correct Way to Cancel an Async Operation That Doesn't Accept a Cancellationtoken
How to Change Pixel Color of an Image in C#.Net
Efficient Way to Round Double Precision Numbers to a Lower Precision Given in Number of Bits
How to Write a Comment to an Xml File When Using the Xmlserializer
An Efficient Way to Base64 Encode a Byte Array
Regex to Match All Us Phone Number Formats
Return All Enumerables with Yield Return at Once; Without Looping Through