IchBestäube IchBestäube - 15 days ago 5
C# Question

Casting generic classes? -> Confusing result

Bofore I would like to ask my question, please read the follwing classes:

public class JsonPackage<A> : USOPackage
{

public JsonPackage(PackageHeader header, object o) : base(header, StringCompressor.CompressString(JsonConvert.SerializeObject(o, Formatting.Indented))) { }


public new A Content
{
get
{
return JsonConvert.DeserializeObject<A>(this.getContentAsString());
}
}


new public string getContentAsString()
{
return StringCompressor.DecompressString(base.getContentAsString());
}
}


(this class includes USOPackage(!))

and a second class:

public class LoginResponsePackage : JsonPackage<LoginResponse>
{

public LoginResponsePackage(LoginResult result) : base(PackageHeader.USO_AUTH_LOGIN_RESPONSE, new LoginResponse(result)) { }


public class LoginResponse
{
public LoginResult Result;
public LoginResponse(LoginResult r)
{
this.Result = r;
}
}

public enum LoginResult
{
OK,
FailedPassword,
FailedUsername,
FailedProtocolVersion
}
}


Now I would like to convert a "USOPackage" to an "LoginResponsePackage" to get the "Content" of the package in the right type.

If i do it like that:

JsonPackage<LoginResponsePackage.LoginResponse> responsePackage = (JsonPackage<LoginResponsePackage.LoginResponse>)usopackage;


So if I try to get "Content" it works which means i get a LoginResponse by calling

responsePackage.Content


but when i convert the class like that

LoginResponsePackage responsePackage = (LoginResponsePackage)usopackage;


I am not able to access the LoginReponse. It just give me access to for instance: BeginInvoke(), Method, Target, Clone()
I don't know where this comes from..

So my question is what do i have to change in my code to be ablt to directly cast the package so i get a "LoginResponse" by accessing "LoginResponsePackage.Content"

Answer

The problem is in this line of code:

public class LoginResponsePackage : JsonPackage<LoginResponse>

The type LoginResponse in this context doesn't mean the nested class you've defined in LoginResponsePackage, it refers to some type outside the class, I guess a delegate from your description of the methods there. You are not inside the class scope yet, so you have to refer to the nested type via its name you would use outside the class: LoginResponsePackage.LoginResponse.
The fixed line:

public class LoginResponsePackage : JsonPackage<LoginResponsePackage.LoginResponse>