Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and non-static version of the same function in C#

I have my own implementation of the GetUserId() function made static to be able to retrieve the ID in static context. But I also have many places where I use standard GetUserId() function built into an asp.net UserManager library. My fix for not using different logic for the same thing is overriding the non-static method and using the static one inside it (this is inside the UserManagerService class):

public override string GetUserId(ClaimsPrincipal user)
{
    return GetUserIdStatic(user);
}

public static string GetUserIdStatic(ClaimsPrincipal user)
{
    return user.FindFirst(ClaimTypes.NameIdentifier).Value;
}

I did that because I prefer to call the non-static method in the non-static context (generally it's over 90% of the calls). So I prefer to call _userManagerService.GetUserId(User) than UserManagerService.GetUserIdStatic(User) whenever I can.

From a readability and maintainability perspective (and eventual harmful consequences that I can't foresee right now) is it better to do it the way described above; switch all calls to the static version; or some other way that I didn't think of?

like image 387
m3h0w Avatar asked Jan 01 '26 02:01

m3h0w


1 Answers

Making a static and non-static versions of a method that do the same thing is highly questionable.

You should replace static method to get user id with a static method or a static property to get user manager service. This would let you obtain user id in static context by calling a non-static method:

var userId = StaticGetUserManagerSerice().GetUserIdStatic(user);

or

var userId = UserManagerSerice.Instance.GetUserIdStatic(user);
like image 179
Sergey Kalinichenko Avatar answered Jan 03 '26 15:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!