11 Replies - 391 Views - Last Post: 28 January 2013 - 01:56 PM Rate Topic: -----

#1 rugbylad28  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

static confusion - methods and rules

Posted 28 January 2013 - 12:16 PM

Hi I am fairly new to C#, but studied one module of VB at university..

now i have grabbed the concepts of classes, inheritance, constructors etc..

but what i am struggling with is the definition and using of Static. Am i right in thinking static variables and methods do not need initialised, and can only call variables from their own class?

what confuses me is that I see a lot of tutorials and examples initialising class variables / properties from other classes within a STATIC Void MAIN method.. Which is confusing as i thought that static methods could only call static variables / methods..

can anyone explain this in lehman terms for me about static variables, methods and things like that.

Is This A Good Question/Topic? 0
  • +

Replies To: static confusion - methods and rules

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5517
  • View blog
  • Posts: 11,826
  • Joined: 02-June 10

Re: static confusion - methods and rules

Posted 28 January 2013 - 12:29 PM

static is better thought of as "one instance across all implimentations"

Let's say you have a class of DisplayMonitors and you use that in various classes in your program.

It would be silly to make numerious instances of DisplayMonitors since they all would have identical information for your screens.

You could make a static DisplayMonitors so when you set 'PreferredStartupScreen' in one class that same one and only shared instance is used by all other classes.
Was This Post Helpful? 0
  • +
  • -

#3 AdamSpeight2008  Icon User is online

  • MrCupOfT
  • member icon


Reputation: 2262
  • View blog
  • Posts: 9,465
  • Joined: 29-May 08

Re: static confusion - methods and rules

Posted 28 January 2013 - 12:29 PM

Think of static as defining a method or member that is shared among all instances of that class or structure.

class Example
{
  static readonly System.DateTime _BirthTime;
  public static Example()
  {
    /* Static Constructor */
    _BirthTime = System.Date.Now();
  }
  public Example()
  {
   /* Instance Constructor */
  }
}


This post has been edited by AdamSpeight2008: 28 January 2013 - 12:30 PM

Was This Post Helpful? 0
  • +
  • -

#4 rugbylad28  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

Re: static confusion - methods and rules

Posted 28 January 2013 - 12:32 PM

I understand that they're mostly used to save time, but i am confused about static methods being able to make new instances of non-static class variables (initialising new) within a static method, i didnt think this was possible. :helpsmilie:
Was This Post Helpful? 0
  • +
  • -

#5 rugbylad28  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

Re: static confusion - methods and rules

Posted 28 January 2013 - 12:42 PM

am i right in thinking that non static or variable out of the scope of the current class can be called in the Static void Main method by initialising an instance, and this is WHY you need to initialise them ?
Was This Post Helpful? 0
  • +
  • -

#6 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4487
  • View blog
  • Posts: 7,816
  • Joined: 08-June 10

Re: static confusion - methods and rules

Posted 28 January 2013 - 12:49 PM

Quote

I understand that they're mostly used to save time


Not really. They're used when they make sense, not to save time. As others have shown, static properties and fields only exist once; they do not exist individually for each instance of the class itself. It has nothing to do with time, it has to do with whether it's logical to store a value for all instances vs. for a single instance.

Static methods are similar, but different as well. Static methods don't operate on an instance of a class; but they are defined for the class itself. For instance, you can't use the keyword this in a static class, because there is no object reference. However, it also has access to a class's static methods/properties.

Quote

i am confused about static methods being able to make new instances of non-static class variables (initialising new) within a static method, i didnt think this was possible


That's because that's really not what's happening. Remember that anything created in a method is scoped to that method. So in this example:

public class Example{
  public string Name {get; private set;}
  private Example(string name){
    Name = name;
  }

  public static Example CreateNew(string name){
    Example e = new Example(name);
    return e;
  }
}


We're using a static method to create a new instance of Example. e is scoped to the method, so it's neither static nor non-static. It's an instance variable. You have access to the private constructor because the method is defined within the class (and private things are visible to class internals). This is a very contrived example, but the pattern makes sense when you need to do things like a Factory Pattern, in which a base class has a static method that creates an instance of a derived class, based on logic internal to itself.

It's a bit advanced. Just know that static methods don't operate on instances of classes; they do not have an object reference as context.
Was This Post Helpful? 1
  • +
  • -

#7 rugbylad28  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 20-September 12

Re: static confusion - methods and rules

Posted 28 January 2013 - 12:55 PM

so i can make instances of other classes within a static method of another class as long as I create a new instance of that class? what would be the advantages of this, and in the real world are static methods used a lot?
Was This Post Helpful? 0
  • +
  • -

#8 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1362
  • View blog
  • Posts: 3,002
  • Joined: 30-January 11

Re: static confusion - methods and rules

Posted 28 January 2013 - 01:04 PM

You basically just said 'so i can make an instance of a class if I make an instance of a class' - so the answer is yes :P

Advantages? Well just like in any other methods instantiating a class lets you call methods/use attributes of the object. Nothing is different in that case. The only difference is that a class does not need to be instantiated to call static methods of a class, you simply do ClassName.staticMethod(parameters); which is useful in some cases like Helper methods or Utilities.

Can't really say how often they are used as it depends entirely on what you are doing. Personally I tend to right a lot of Utility methods which means I probably use static more than some others. That being said on normal development I rarely find a good usage of it. Only use it when the situation makes calls for it. You see a lot of developers overuse it for convenience making some horrible code in the process.
Was This Post Helpful? 0
  • +
  • -

#9 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4487
  • View blog
  • Posts: 7,816
  • Joined: 08-June 10

Re: static confusion - methods and rules

Posted 28 January 2013 - 01:12 PM

You're wrapping yourself around terminology you don't understand, and it's causing a problem. Try not to get hung up on the words and try to understand the concepts of what is happening.

The example I gave is an extremely basic Factory Patttern. Look that up for more examples on why you might do that.

Quote

and in the real world are static methods used a lot?


How to answer a question like this? In a word, "yes", but I'm sure you want more context than that. It's just another tool in the box. Once you understand how to use the tool, you use it where it makes sense. When you want to define a method on a class, but you don't need to operate on an instance of the class itself, then you make it static. Often, static methods are "utility methods", that you don't need to be attached to any specific instance, but you want to be able to use, and the class is a logical place to put it.

Example: the string class. It has many methods, both static and non-static:

Let's look at two of string's methods: Substring and IsNullOrWhiteSpace

Substring is a non-static method. That means that the method operates on the instance it was called on. Example:

var s = "this is a string.";
var ss = s.Substring(3);


The internal logic of Substring has access to s and can operate on it, in this case returning a partial string from it.

Now, IsNullOrWhiteSpace is a static method. It has to be static. Take the following example:

var s1 = null;
var s2 = "   ";
var s3 = "...";
Console.WriteLine(string.IsNullOrWhiteSpace(s1));
Console.WriteLine(string.IsNullOrWhiteSpace(s2));
Console.WriteLine(string.IsNullOrWhiteSpace(s3));


In this case, because the string that will be tested can (and indeed will frequently be) null you can't make it an instance method, because you can't call methods on a null reference. If you try, you get a null reference exception.

However, it still makes sense for this method to "belong" to the string class, because it is a string utility. Where else would it go? So, they make it a static method on the string class.
Was This Post Helpful? 0
  • +
  • -

#10 AdamSpeight2008  Icon User is online

  • MrCupOfT
  • member icon


Reputation: 2262
  • View blog
  • Posts: 9,465
  • Joined: 29-May 08

Re: static confusion - methods and rules

Posted 28 January 2013 - 01:13 PM

View PostCurtis Rutland, on 28 January 2013 - 08:49 PM, said:

For instance, you can't use the keyword this in a static class, because there is no object reference.


Yes you can but only in a specific purpose, to define an extension method.

static public class Exts
{
  static public Int CountOfNonWhitespace(this string s)
  {
    return s.Where( c=> !Char.IsWhiteSpace(c)).Count();
  }
}


Was This Post Helpful? 0
  • +
  • -

#11 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4487
  • View blog
  • Posts: 7,816
  • Joined: 08-June 10

Re: static confusion - methods and rules

Posted 28 January 2013 - 01:15 PM

True, but that really has a different context, since it's 1) an extension method, and 2) used in the parameter list and not the method body. Yes, extension methods are just syntactic sugar for simple static methods, but it makes it easier to discuss static methods for novices by excluding them from the conversation.
Was This Post Helpful? 0
  • +
  • -

#12 h4nnib4l  Icon User is offline

  • The Noid
  • member icon

Reputation: 1181
  • View blog
  • Posts: 1,675
  • Joined: 24-August 11

Re: static confusion - methods and rules

Posted 28 January 2013 - 01:56 PM

Here's a good example of using a static class that I'm dealing with right now. We have an application with dozens of modules, each of which has windows that it opens. Without going into the details of the problem, basically the windows' WindowStates (maximized, minimized, normal) are being reset every time a new window opens. Now, every time a module is used, an "instance" of it is being created. If we close that window, that instance is gone. If we reopen it, there's a new instance. The solution that I am implementing is to create a static StateManager that, you guessed it, manages the state of the windows opened in the application. StateManager is static because each module doesn't need an instance, they all HAVE to be using the exact same StateManager that exists beyond their scope, or it wouldn't be able to serve all of them simultaneously. It isn't an issue of size or scope, but responsibility. We don't need StateManager instances coming and going, or it would be ineffective at maintaining state: we need one omniscient class that handles it without every being explicitly told to exist.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1