Click here to Skip to main content
15,845,785 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Could someone please explain briefly how I create a static variable in a static class

In my code below I can create the Document and Element varaibales fine,
So how do I create a varaible from a static class that I have created?

C#
public static class Settings
{
    public static FileInfo Database;
    public static XmlDocument Document;
    private static XmlElement Element;
}

public static class FileInfo
{
    public static string Location;
    public static DateTime Date;
}

The reason is simply to understand the static process further.

Thanks for your answers.
Posted
Comments
Grant Mc 28-Mar-13 6:22am    
OK, still a little confused. I now have this

public partial class Form1:Form
{
public void Test()
{
Settings.Database.Location = "Test"; // This produces a error
}

public static class Settings
{
public static FileInfo Database;
public static XmlDocument Document;
private static XmlElement Element;
}

public class FileInfo
{
public string Location = "Test";
public DateTime Date;
}


But it produces a runtime error
System.NullReferenceException

Why is it doing this please?
Grant Mc 28-Mar-13 6:40am    
Figured it out.

I thought that because it was static that I did not have to do
Database = new FileInfo()

Thanks for everyone's assistance.
I have learned something for today.

You can't create an instance of a static class. The whole reason it is static is because you don't need to do so, since all properties and methods are static.

I suspect you want to make FileInfo non-static (and its properties as well).

Regards,
Ian.

P.S. I would add that the System.IO namespace has a class called FileInfo, which you might want to consider using instead. http://msdn.microsoft.com/en-GB/library/system.io.fileinfo.aspx[^]
 
Share this answer
 
v2
Comments
Grant Mc 28-Mar-13 5:59am    
So why am I allowed to to create an instance of the XmlDocument etc?

Thanks for your assistance.
Zoltán Zörgő 28-Mar-13 6:01am    
Settings.Document = new XmlDocument(....
Ian A Davidson 28-Mar-13 6:04am    
Because XmlDocument is not a static class.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900