Yanick van Barneveld Yanick van Barneveld - 2 months ago 6
C# Question

Print a variable on the screen using Razor (C#)

I want to print a variable on the screen using Razor. I have a class named CustomPrincipal saved in the HttpContext, which is saved correctly.

I want it to have it on one line like the example below, which is unfortunately not working:

@* This is not working... *@
@(CustomPrincipal)Context.Items["IUser"].Name


The example below is working though, so it saved it correctly to the HttpContext.

@{ CustomPrincipal user = (CustomPrincipal)Context.Items["IUser"]; }
@user.Name


Does anyone know why the first example is not working and can you show me a solution?

The error is:


Compiler Error Message: CS0118: 'CustomPrincipal' is a 'type' but is used like a 'variable'

Answer

All the credits go to @DavidG and @CodeCaster, mentioned in the comments.

@(((CustomPrincipal)Context.Items["IUser"]).Name)

The parentheses where required because otherwise there is no Name property on the Object type which is what Context.Items["IUser"] is. We have to add parentheses to cast that Object to CustomPrincipal first, then access the Name property of that type.

Another example of the same problem: http://stackoverflow.com/a/4151988/4585226

Comments