I’ve been going through some tutorials on properties and class variables, and I understand that if you set a class variable (in the example below, bar) then you can then call a type to cast this object to a specific variable (I did not do this in the example below, just to clarify). But what would happen if you used this same class variable, with an object already stored in it to call a method? In reference to the example below, will the “ok” be passed to the method, or is it simply ignored? I tried running this though this compiler and it didn’t seem to have an issue with it, but I’m not sure if it’s actually doing anything with the object bar is set to. Thanks for the Help!
public class Foo
{
public static void Main()
{
Foo bar = new Foo();
object ok = "ok";
bar = (Foo)ok;
bar.genericMethod();
}
public void genericMethod()
{
}
}
No, it’s not. Not sure what you mean by “class variable” – what you have here is two local variables, of types
Fooandobject. The second method has access to neither of them as they are local to the first method. If you want the second method to have access, then you must do one of two things: pass one as a parameter to the second method (so it is defined, for example, asvoid genericMethod(Foo foo)), or declare one of the variables as a field instead, outside of both the methods at class level.Your code will compile, but will fail at runtime at the line
bar = (Foo)ok. Although in principle it might be possible to cast anobjectto aFoo(because aFoois anobject), in practice thisobjectis not, and the cast fails.