0

I have a static variable -

static readonly String tableName;

I tried to set it like this

static readonly String tableName = Dts.Variables["ssisString"].Value.ToString();

I get an error:

An object reference is required for the non-static field, method, or property. 

But, it works like this:

static String tableName = ""; 

main()
{
     tableName = Dts.Variables["ssisString"].Value.ToString();
}

Why ?

ShinyBaldHead
  • 13
  • 1
  • 6

2 Answers2

1

It's not the static part, it's the readonly that is hosing you.

enter image description here

    static readonly String tableName;

    static ScriptMain()
    {
        // An object reference is required for the non-static field, method, or property 'Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase.Dts.get'
        tableName = Dts.Variables["ssisString"].Value.ToString();
    }

    public void Main()
    {
        // this works
        string local = Dts.Variables["ssisString"].Value.ToString();

        // a static read only field cannot be assinged to (except in a static constructor or a variable initializer)
        tableName = Dts.Variables["ssisString"].Value.ToString();

        Dts.TaskResult = (int)ScriptResults.Success;
    }

My poorly remembered information about static is that there is one instance of the variable for all instantiations of the class. Since there's only going to be one instance of ScriptMain, are you getting anything from going static vs an instance variable?

Anyways, one instance of tableName and you want to assign it a value. The problem is, the thing which has the value you want to use has to be instantiated to provide this value. This isn't a problem, as you demonstrate, when it is assigned inside the Main method.

It is a problem though because a readonly property only allows you to assign a value in a static constructor or a variable initializer... which in my head gets back to the problem of needing an instance.

Some .net person, feel free to slag all over this or improve this answer by using the proper terminology.

References

Community
  • 1
  • 1
billinkc
  • 59,250
  • 9
  • 102
  • 159