Yanick van Barneveld Yanick van Barneveld - 7 months ago 53
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... *@

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

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

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'


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


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