Skip to main content

Can't access property inside object initializer

Consider the following code.

List files = new List();
....
while (reader.Read())
{
    var a = new MyFiles
    {
       FileName = reader["Filename"].ToString(),
       FileLocation = reader["Filelocation"].ToString(),
       FullPath = FileLocation + @"\" + FileName // Error at this line
    };
   files.Add(a);
}

The above is a snippet from my method which uses SqlDataReader to fetch data from the database. Everything works fine expect when I try to assign value to FullPath property I get the following error message:

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

I know I can make those properties static or create an instance and access them via e.g. var b = new MyFiles(); b.FileLocation ..

But my question is why can't I use FileLocation and FileName as I am in the above code snippet. Is there something I'm missing?

Solved

You cannot access the property of an instance which you are just initializing.

You can use local variables:

int fileNameColumnOrdinal = reader.GetOrdinal("Filename");
int fileLocationColumnOrdinal = reader.GetOrdinal("Filelocation");
while (reader.Read())
{
    string fileName = reader.GetString(fileNameColumnOrdinal);
    string fileLocation = reader.GetString(fileLocationColumnOrdinal);
    var a = new MyFiles
    {
       FileName = fileName,
       FileLocation = fileLocation,
       FullPath = System.IO.Path.Combine(fileLocation, fileName)
    };
   files.Add(a);
}

I also recommend to use System.IO.Path.Combine.


When creating a new object and set some properties using this syntax: var foo = new bar { a = 123 }; You can only set properties, not using them. You have to use some helper variables or setting the properties via: foo.a = 456;.

Solution 1

List files = new List();
....
while (reader.Read())
{
    string fileName = reader["Filename"].ToString();
    string fileLocation = reader["Filelocation"].ToString();

    var a = new MyFiles
    {
       FileName = fileName,
       FileLocation = fileLocation,
       FullPath = fileLocation + @"\" + fileName // Error at this line
    };
   files.Add(a);
}

Solution 2

List files = new List();
....
while (reader.Read())
{
    var a = new MyFiles()

    a.FileName = reader["Filename"].ToString();
    a.FileLocation = reader["Filelocation"].ToString();
    a.FullPath = a.FileName + @"\" + a.FileLocation // Error at this line
   files.Add(a);
}

Solution 3

You can create a custom getter for FullPath:

public string FullPath
{
    get { return FileName + @"\" + FileLocation; }
}

EDIT

I think there is no specific reason for this. It's by design, so some c# developer thought, we don't need this :) I think it would be possible, but just not implemented. It should be possible, because the created IL-Code is the same as in my solution 2 and it is only some syntactical sugar.


Comments

Popular posts from this blog

Could not run elki.sh in mac OSX

In order to use ELKI to do a clustering task, I have downloaded the latest complete release package: elki-0.7.1 The README.PDF says to run elki.sh on OSX. However, after I run the elki.sh with Terminal, it pops the following error: Error: Could not find or load main class de.lmu.ifi.dbs.elki.application.ELKILauncher I am sure I have downloaded the complete packages entirely, but still could not run ELKI successfully. Thanks in advance! Solved I will show below how you can install Elki in macOS, El Capitan Version 10.11.6. Installation of ELKI in macOS brew cask install java git clone https://github.com/elki-project/elki.git cd elki ./gradlew shadowJar ./gradlew build open elki-bundle-0.7.2-SNAPSHOT.jar where you can see the ELKILauncher. Example that ELKI is working just fine Background You don't have to configure any paths, actually. Questions you may want to ask yourself are Did you build the Elki on the command line? Do y...

Getting s.Type.ToUpperCase() is not a function when calling WCF service with $ajax

I'm using WCF and I am getting this error. If I use jQuery1.14.1 I get Type error: s.type.ToUpperCase is not a function type = s.type.ToUpperCase(); If I use jQuery 1.12.1 locally the service gets called corrctly. However, if I try it on the server, 1.14.1 get the error above, but 1.12 i get this one: Type error: l.type.ToUpperCase() is not a function ..+&&n.event.trigger("ajaxStart"),l.type=l.type.ToUpperCase(), l,hasContent=!Kb.tes.... Relevant code: var Type = "POST"; var DataType = "jsonp"; var ProcessData = true; var ContentType = "application/json; charset=utf-8"; var params = { user: $("#userid_hidden").val().toString(), permission: $("#permission_id_" + i).val().toString(), enabled: true, note: $("#permission_note_" + i).val(), write: $("#permission_write_" + i).is(":checked") } SetPermission(params); function SetPermission(p...