Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use static type instead of variable

Tags:

c#

Is there any way to tell the compiler to use a static type instead of a variable when your project doesn't use namespaces?

For instance, I have a class called User with various static and non-static methods. Let's say one of the static methods is called GetUser().

I'm trying to call that User.GetUser() method from a method that also has a variable in scope (inherited from base class) called User. However, the compiler complains saying that it can't find User.GetUser() because it thinks I'm referring to the User variable that's in scope.

If this project used namespaces, I could just do ns1.User.GetUser(), but that's not feasible in this case. Is there a way that I can tell the compiler that I'm referring to the User type instead of the User variable?

like image 343
itsme86 Avatar asked Jan 14 '13 18:01

itsme86


People also ask

Can you change the static type of a variable?

Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods.

Is it better to work with static or dynamic data types?

Static Data structure has fixed memory size whereas in Dynamic Data Structure, the size can be randomly updated during run time which may be considered efficient with respect to memory complexity of the code. Static Data Structure provides more easier access to elements with respect to dynamic data structure.

Which is a commonly claimed benefit of using statically typed language?

Protection from Runtime Errors This is the main benefit of statically typed languages. Many runtime errors become compile time errors as the compiler ensures that you are writing 'correct' code. This leads to a much smoother development experience.

Are statically typed languages faster?

Static typing usually results in compiled code that executes more quickly because when the compiler knows the exact data types that are in use, it can produce optimized machine code (i.e. faster and/or using less memory).


1 Answers

You can use:

global::User.GetUser()

Or a using directive to alias the type:

using UserType = User;

...

UserType.GetUser();

I'd strongly encourage you to use namespaces though :)

like image 174
Jon Skeet Avatar answered Oct 04 '22 10:10

Jon Skeet