Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Newbie question on using classes
Message
From
10/12/2009 17:49:23
 
General information
Forum:
ASP.NET
Category:
Other
Environment versions
Environment:
C# 2.0
Miscellaneous
Thread ID:
01438397
Message ID:
01438514
Views:
52
Dmitry,

It might be a good idea if you could tell us what you plan to do with this class. The reason I say that is because, since you're new to .NET, you may or may not "get" the point of using static methods/properties.

As Gregory's example with the Person class pointed out, you wouldn't want to use Birthdate as a static property because that would be different in every instance of the Person class. If it wasn't obvious from his explanation, I just wanted to clarify that when you use static properties they will contain exactly the same values in every instance of the class. If you have several instances of the class, and in one instance you decide to make a change to a static property, then all the other instances of that class will automagically have that new value. If this is the kind of thing you want, then all is good.

Now, I know your specific question was about a static method, not property, but depending on what your method does it may need to use static properties ... so it may still be relevant to your question

~~Bonnie


>>>>>
>>>>>TIA.
>>>>
>>>>
>>>>Dmitry,
>>>>
>>>>If the method of the class is not marked as static, you have to instantiate the class prior to calling the method
>>>>
>>>>var obj = new MyClassName();
>>>>obj.MethodName();
>>>>
>>>>
>>>>If the method of the class has been marked as static, you can call it without instantiating the class
>>>>
>>>>
>>>>
>>>>// class definition
>>>>public class MyClassName
>>>>{
>>>>
>>>>public static MethodName()
>>>>{
>>>>}
>>>>}
>>>>
>>>>
>>>>// then call like this
>>>>MyClassName.MethodName()
>>>>
>>>
>>>Thank you, Gregory. This explains what I was missing. It looks like having methods marked as static makes it easier to use them. Is there much downside to it, as far as you know?
>>
>>Static methods can only use static methods and static fields - unless an object is passed as a parameter
>>
>>
>>It depends .
>>
>>In a Person's class, a BirthDate would be an instance property - since it's different for each person
>>
>>The method to calculate the age would not be static, since it will access the BirthDate of the instance
>>
>>Sample
>>
>>public class Person
>>  public DateTime BirthDate;
>>
>>  public int CalcAge()
>>  {
>>     // use BirthDate, ie this.BirthDate
>>  }
>>}
>>
>
>Thank you for the explanation.
Bonnie Berent DeWitt
NET/C# MVP since 2003

http://geek-goddess-bonnie.blogspot.com
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform