0

I'm working on a console application which also had reference to class library. In class library i have following code.

namespace SomeClass  
{  
    public class ClassOne  
    {  
        public string[] SupportedFiles;  
    }  
} 

And in console app, program.cs, i'm trying to assign SupportedFiles.

class Program  
    {  
        public ClassOne class1 { get; set; }  
        public Program()  
        {  
            class1.SupportedFiles = new string[] { "Test", "Test" };
           //class1.SupportedFiles[0] = "First";
           //class1.SupportedFiles[1] = "Second"; 
        }  
    }

But the line class1.SupportedFiles = new string[] { "Test", "Test" }; throws

System.NullReferenceException: 'Object reference not set to an instance of an object.'

What am i missing? Am I so dumb instantiating a string array. Please help me out.

Learn Avid
  • 59
  • 2
  • 13

2 Answers2

1

You are missing instance of class where string[] is present

Try with this before accessing string[]

ClassOne cOne = new ClassOne();

Do not miss adding reference of your class library to project where you want to access this string and also include namespace in program.cs file

This can be your working solution:

using SomeClass;
class Program  
    {  
        //Not required to create property of ClassOne
        //public ClassOne class1 { get; set; }  
        public Program()  
        {  
           //In this way, you can create instance of class.
           ClassOne class1 = new ClassOne();
           //Now with the help of instance of class, you can access all public properties of that class
            class1.SupportedFiles= new string[] { "Test", "Test" };
           //class1.SupportedFiles[0] = "First";
           //class1.SupportedFiles[1] = "Second"; 
        }  
    }
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

You have to initialize your object before accessing its members. For that you have several(basic) options:

class Program  
{  
    public ClassOne Class1 { get; set; }  
    public Program()  
    {  
        Class1 = new ClassOne();
        Class1.SupportedFiles= new string[] { "Test", "Test" };
    }  
}

or even better:

class Program  
{  
    public ClassOne Class1 { get; set; }  
    public Program()  
    {  
        Class1 = new ClassOne()
        {
            SupportedFiles = new string[] { "Test", "Test" }
        };
       //class1.SupportedFiles[0] = "First";
       //class1.SupportedFiles[1] = "Second"; 
    }  
}

or if you're using C#6 and above, you have such thing as auto-property initializers:

class Program  
{  
    public ClassOne Class1 { get; set; } = new ClassOne();
    public Program()  
    {  
        Class1.SupportedFiles= new string[] { "Test", "Test" };
       //class1.SupportedFiles[0] = "First";
       //class1.SupportedFiles[1] = "Second"; 
    }  
}
SᴇM
  • 7,024
  • 3
  • 24
  • 41