-3

I have the following class:

public class Example
{
    public static string GetName(string username)
    {
        //Code to retrieve record from database
        return RetrievedString;
    }
}

I use this to get a user's name to some functions that need it (e.g putting user's name in session on login etc.).

The code works. My confusion is if it's correct to have this be a static string or whether I should just make it non static and initialize an object and use the GetName as a property to retrieve the string.

Keep in mind that multiple users will be online concurrently.

user4483037
  • 49
  • 1
  • 8
  • Best not to have static methods that have code to access database. You may run into issues disposing off resources (ex: connections etc). See this answer for more on why what you have is a bad idea => http://stackoverflow.com/a/21414281/325521 – Shiva Dec 22 '15 at 07:50
  • 2
    Here is your answer: [Static Variable vs Static Method](http://stackoverflow.com/questions/11402907/difference-between-static-variables-and-static-methods). Hope this get's rid of your confusion between the two. – Suprabhat Biswal Dec 22 '15 at 08:04
  • @SuprabhatBiswal I know the difference between the two. My confusion is that since the RetrievedString is dependent on the input string username which is always unique (which is then used in a SELECT [Name] FROM [Talbe] WHERE Name = @username), is there a reason that this should not be static? – user4483037 Dec 22 '15 at 08:20
  • @user4483037: Did you visited the link I mentioned above. The answer you are looking for is mentioned on that post. – Suprabhat Biswal Dec 22 '15 at 08:38
  • 1
    @SuprabhatBiswal I just saw this from the answer you linked: "If the method uses only call parameters and local variables, and the call parameters are not themselves pointing to statisc member variables, calls from different users will not affect each other." Thank you, that was what I was looking for. – user4483037 Dec 22 '15 at 09:17
  • Welcome, Pleasure helping you out. – Suprabhat Biswal Dec 22 '15 at 09:42

1 Answers1

0

Remember that static means that current field/property/method is a member of a type, not an instance. Static members exist on type level and are shared between all instances of a type.

Generally you don't want to store in a static member anything that should be unique. Good use case is e.g. connection factories, which have static access but generate unique connections.

In your example it all depends on the implementation - this is basically a helper class and make it usable you have to pass all connection logic inside it. This doesn't seem like a good idea, especially if you would like to mock connection/result. If you really want to make it static, I'd go with extension method on your connection object so it is easy to use and get it having your connection mockable and injectable.

kamil-mrzyglod
  • 4,948
  • 1
  • 20
  • 29