Is this really a good construction

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

A have this small FileInformation class
public class
{
public string Id { get; set; }
}

In some other place in the code I have this kind of statement
anObject.Add(new FileInformation {Id = strCurrentFileId});

The definition of Id in FileInformation is completely new to me because this
doesn't
exist in 2.0.

Does this mean that you define both a field and a propety(get and set) with
name id with access right as
public ?

I have been learned that defining a field as public is not a good thing to
use OOP

//Tony
 
Tony Johansson said:
Hello!

A have this small FileInformation class
public class
{
public string Id { get; set; }
}

In some other place in the code I have this kind of statement
anObject.Add(new FileInformation {Id = strCurrentFileId});

The definition of Id in FileInformation is completely new to me because
this doesn't
exist in 2.0.

Does this mean that you define both a field and a propety(get and set)
with name id with access right as
public ?

I have been learned that defining a field as public is not a good thing to
use OOP

Its short hand syntax for :-

string m_Id;
public string Id
{
get { return m_Id; }
set { m_Id = value; }
}

Note the field is not defined public its private but the property methods
get and set are available publically.

An alternative would be:-

public class FileInformation
{
public FileInformation(string id) { Id = id; }
public string Id { get; private set; }
}

anObject.add( new FileInformation(strCurrentField));

This would allow for the construction of the object given an ID but the id
would then be read-only to code external to the class.
 
A have this small FileInformation class
public class
{
    public string Id { get; set; }

}

In some other place in the code I have this kind of statement
anObject.Add(new FileInformation {Id = strCurrentFileId});

The definition of Id in FileInformation is completely new to me because this
doesn't exist in 2.0.

Does this mean that you define both a field and a propety(get and set) with
name id with access right as public ?

The field is private, the property is public. This is called an
automatically implemented property.
I have been learned that defining a field as public is not a good thing to
use OOP

Indeed, but an automatically implemented property doesn't do that.

The way of creating the FileInformation instance is called an object
initializer btw, and is also new with C# 3. It doesn't rely on the
property being an automatically implemented one though.

Jon
 
Back
Top