How do I access the nested Class? [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have the following three classes defined.
public class FrequencyRecord
{
public double Frequency;
public int Duration;
}
public class EntryRecord
{
public string Name;
public Boolean Status;
public long TotalTime;
public FrequencyRecord[] FreqTime = new FrequencyRecord[25];
public string Description;
}
public class Salv7Profile
{
public string Version;
public string SoftVersion;
public string Name;
public DateTime CreateDate;
public DateTime LastModDate;
public int Count;
public EntryRecord[] Entries = new EntryRecord[99];
public int Type;
}
Then I create an instance:
public static Salv7Profile IntProfile = new Salv7Profile();
Assigning a value to:
IntProfile.Name = "Peter";
works fine, But if I try:
IntProfile.Entries[1].Name = "Peter";
It throws an error: [System.NullReferenceException] "Object reference not set to an instance of an object."}
Being a novice at C#, how do I access the nested Entries class?

The problem is that you've created an array, but that array is just full of null references to start with. You'd need something like:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries[1] = record;
to replace the array element with a reference to the newly-created EntryRecord.
It would almost certainly be better if you changed Entries to be a List<EntryRecord> though, and just used:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries.Add(record);
or more briefly, using an object initialzier:
IntProfile.Entries.Add(new EntryRecord { Name = "Peter" });
I would also strongly recommend against having public fields; use properties instead, and consider making your types immutable if you can.
(I'd encourage to think about whether you really need the IntProfile field to be static, too... static fields imply global state, which is harder to test and reason about.)

Related

Anonymous type with var gives error CS0825 [duplicate]

This question already has answers here:
Implicit typing; why just local variables?
(6 answers)
Closed 1 year ago.
I want to create an anonymous type in C# inside a class.
The examples I have seen use var to create an anonymous variable
var RecordId = new
{
Foo = 0,
Bar = "can be also a string"
};
However I want to create my anonymous variable inside a class.
public class Logger //: LogBase
{
var RecordId = new
{
Foo = 0,
Bar = 1
};
}
So when Logging I can do:
Logger.RecordId.Foo
But declaring my anonymous type as var triggers the following error:
CS0825: The contextual keyword 'var' may only appear within a local variable declaration.
What is the type of an anonymous variable, so I don't have to use var?
I understand what the error is telling me, but I don't want to move my variable inside a function, it needs to be a property of Logger.
Edit: enum is what I tried t the beginning, but I need the values to be more flexible than just integers (like strings, so I can dump jon files).
I updated my question to reflect that.
var (and by definition anonymous types) can only be declared inside a method, the error message is basically telling you that. If you need this type to be at class level, then make a class/struct/tuple to store it.
public static class Record
{
public static int Foo { get; set; }
public static int Bar { get; set; }
}
public class Logger //: LogBase
{
public static Record RecordId { get; set; } = new Record();
}
Now you can do this:
var foo = Logger.RecordId.Foo;
Note that I also used static so you don't need to create a new instance of the class, but change that if you think it's relevant.
public class Logger //: LogBase
{
public enum RecordId
{
Foo = 0,
Bar = 1
}
}
If you do not want strings you can do the above.
public class LogCategory
{
private LogCategory(string value) { Value = value; }
public string Value { get; private set; }
public static LogCategory Foo { get { return new LogCategory("Foo"); } }
public static LogCategory Bar { get { return new LogCategory("Bar"); } }
}
If you want strings you could create your own class something like the above.
You can use the dynamic type to have an anonymous instance variable.
public class Foo
{
dynamic bar = new {
A = 1,
B = 2
};
public void Print() {
Console.WriteLine(bar.A);
}
}
Try it out!
Just because you can do this doesn't mean it's a good idea. See DavidG's answer for an alternative using a strongly-typed object that will not require you to expose your code to the many problems associated with the dynamic type.

Null reference on static class property [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I have a static class:
public static class Options
{
public static MiscSettings MiscSettings;
public static Units Units;
}
My definitions for the two property classes looks like this:
[Serializable]
public class Units
{
public LengthUnit LengthUnit { get; set; } = LengthUnit.Millimeter;
public VolumeUnit VolumeUnit { get; set; } = VolumeUnit.CubicCentimeter;
}
[Serializable]
public class MiscSettings
{
public bool OutputDebugging { get; set; } = false;
}
When I do:
Options.Units = OptionsData.Units;
Options.MiscSettings.OutputDebugging = false;
The first line executes ok. The second gives me a NullReference Exception. The property Options.MiscSettings is null. The next error is Object not set to an instance of an object.
I've tried renaming everything, changing order of the properties. I also tried moving the property OutputDebugging to the Units class and that worked just fine.
Any help would be appreciated.
Just because a field is static doesn't mean you don't have to initialize it. Here, MiscSettings is never initialized, so it's null, and when you try to set its OutputDebugging you get the aforementioned NullReferenceException.
One easy way to to set OutputDebuggin would be to initialize MiscSettings with an object initializer:
Options.MiscSettings = new MiscSettings
{
OutputDebugging = false;
}
try this
if(Options.MiscSettings==null) Options.MiscSettings=new MiscSettings();
Options.MiscSettings.OutputDebugging = false;
When you are creating a class object, you need to make sure to initialize the variables you will use. The MiscSettings variable is not set, therefore you are getting a NullReferenceException.Options.MiscSettings = new MiscSettings();

in C# in LIST I am not able to assign a value [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
Here request is the LIST with the "sortcolumns" property, so Initialy it "sortcolumns" is null so programmatically I am trying to assign a two values which are part of sort columns
request.SortColumns.Add( new SortColumn() { Name = "PolicyName", Direction = DirectionType.Descending });
I am always getting this error, please let me know why - Object reference not set to an instance of an object.
here
public class SortColumn
{
public string Name { get; set; }
public DirectionType Direction { get; set; }
}
You seemingly need to initialize the list before you start adding to it (once)
request.SortColumns = new List<SortColumn>();
This might be in the constructor of the request, it might be before you Add code, you might even make it a intialised property of the class itself
Example of Property Intialization
public class SomeRequest
{
public List<SortColumn> SortColumns {get;set;} = new List<SortColumn>();
...
Example of Constructor Intializer
public class SomeRequest
{
public SomeRequest()
{
SortColumns = new List<SortColumn>();
...
You need to initialise the property before you use it, try this:
request.SortColumns = new List<SortColumn>();
request.SortColumns.Add( new SortColumn() { Name = "PolicyName", Direction = DirectionType.Descending });

What is the benefit of using get and set properties in this example? [duplicate]

This question already has answers here:
What is the difference between a field and a property?
(33 answers)
Auto-properties with or without backing field - preference?
(1 answer)
Closed 8 years ago.
What is the benefit of using get and set properties in the following example?:
class Program
{
public class MyClass
{
private int age;
public int persons_age
{
get
{
return age;
}
set
{
age = value;
}
}
}
static void Main(string[] args)
{
MyClass homer = new MyClass();
homer.persons_age = 45; //uses the set property
homer.persons_age = 56; //overwrites the value set by the line above to 56
int homersage=homer.persons_age; //uses the get property
Console.WriteLine(homersage);
}
}
what is the difference between doing that and the following?:
public class MyClass
{
public int age;
}
static void Main(string[] args)
{
MyClass homer = new MyClass();
homer.age = 45;
homer.age = 56; //overwrites the value set by the line above to 56
int homersage=homer.age;
Console.WriteLine(homersage);
}
What is the benefit of using the get and set property when there is no difference at all in what the above two programs do? Unlike the scenario where the client has limited ability to assign vales to the field via the set method through some logic checking, in this situation I don't see any functional difference between the two programs show here.
Also, some programming books use the phrase "...breaks the client code" if such properties are not used for class fields. Can someone explain this?
Thanks.
One answer I can think of is that with setter and getter methods, you can add checking or validation in it. unlike accessing it directly by declaring it public, the checking/validation will fall out on a different location and a possible duplication of codes.
example:
public class MyClass
{
private int age;
public int persons_age
{
get
{
return age;
}
set
{
if(value > 0)
age = value;
else
//do something here
}
}
}
this way you are defining constraints on your objects.

The this reference? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When do you use the “this” keyword?
Can anyone explain me the "this" reference? when we use this ? with a simple example.
When you use this inside a class, you're refering to the current instance: to the instance of that class.
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName) {
//How could you set the first name passed in the constructor to the local variable if both have the same?
this.firstName = firstName;
this.lastName = lastName;
}
//...
}
In the above example, this.firstName is refering to the field firstName of the current instance of the class Person, and firstName (the right part of the assignment) refers to the variable defined in the scope of the constructor.
So when you do:
Person me = new Person("Oscar", "Mederos")
this refers to the instance Person instance me.
Edit:
As this refers to the class instance, cannot be used inside static classes.
this is used (too) to define indexers in your classes, like in arrays: a[0], a["John"],...
this is a scope identifier. It is used within an object's instance methods to identify behaviors and states that belong to an instance of the class.
Nowadays-fashionable Fluent APIs use this extensively. Basically it's used to get hold of a reference to the current instance.
here's a simple example
public class AnObject
{
public Guid Id { get; private set;}
public DateTime Created {get; private set; }
public AnObject()
{
Created = DateTime.Now;
Id = Guid.NewGuid();
}
public void PrintToConsole()
{
Console.WriteLine("I am an object with id {0} and I was created at {1}", this.Id, this.Created); //note that the the 'this' keyword is redundant
}
}
public Main(string[] args)
{
var obj = new AnObject();
obj.PrintToConsole();
}

Categories

Resources