Double Instantiation in C# [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed last month.
I have the following classes:
public class Coordinates
{
public double x;
public double y;
}
public class WaferAlignment
{
public Coordinates upper1 { get; set; }
public Coordinates upper2 { get; set; }
}
And here's part of my code:
public partial class MainWindow : Window
{
WaferAlignment calc = new WaferAlignment();
public MainWindow()
{
InitializeComponent();
}
public void ButtonCalculate_Click(object sender, RoutedEventArgs e)
{
try
{
calc.lower1.x = Convert.ToDouble(Lower_X_TextBox0.Text);
calc.lower1.y = Convert.ToDouble(Lower_Y_TextBox0.Text);
}
}
I've been getting a "Object Reference Not Set to an Instance of an Object" error and I'm almost certain it has to do with me not being able to instantiate Coordinates. I just don't know how or where I should do it. Please understand I'm still a bit new with this and I'd appreciate any guidance.

You need to initialize upper1 and upper2.
public class WaferAlignment
{
public Coordinates upper1 { get; set; } = new Coordinates();
public Coordinates upper2 { get; set; } = new Coordinates();
}

Related

System.NullReferenceException when i try to add a value to my List [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 27 days ago.
I got a class who looks like this.
public class PostUndKey
{
public string Key { get; set; }
public List<int> Id { get; set; }
public List<string> von_datum { get; set; }
public List<string> bis_datum { get; set; }
}
In my Code i use something like this.
PostUndKey x = new PostUndKey();
var z = 42;
x.Id.Add(z);
And i always get the Null Reference Exception.
Can someone explain this to me pls i dont get it.
Thanks
You need to create an instance of List<int> and assign it to Id property. List<T> is a reference type and default value for reference type is null. For example:
PostUndKey x = new PostUndKey();
x.Id = new List<int>();
var z = 42;
x.Id.Add(z);
Or initialize Id for PostUndKey instance creation:
public class PostUndKey
{
public string Key { get; set; }
public List<int> Id { get; set; } = new List<int>();
public List<string> von_datum { get; set; }
public List<string> bis_datum { get; set; }
}
Read more:
Auto-Implemented Properties
Reference types

How to properly use class as property for another class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed last month.
Here I have this class which is basically a data structure:
public class Config
{
public uint? Release { get; set; }
public string InstallPath { get; set; }
public uint? CheckEveryXMinutes { get; set; }
public override string ToString()
{
return $"(Release: {Release}, InstallPath: {InstallPath}, CheckEveryXMinutes {CheckEveryXMinutes})";
}
}
And I want to use this structure as property of another class like this:
public class ConfigRegistry
{
public Config Result { get; set; }
public ConfigRegistry (string registryKey)
{
Result.Release = 0;
Console.WriteLine("Read Release from registry: {0}", Result.Release);
}
}
And I'm getting an error at "Result.Release = 0" line:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
What am I doing wrong here?
I needed to add
Result = new Config();

"If is class" Condition Failing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
Hi I have 3 base interfaces:
public interface IKlarfDefect
{
int TEST { get; set; }
int DEFECTID { get; set; }
}
public interface IKlarfDefect <TImageListInfo> : IKlarfDefect
{
List<TImageListInfo> KlarfImageList { get; set; }
}
public interface IHasKlarfImageList<TImageListInfo>
{
List<TImageListInfo> KlarfImageList { get; }
}
These classes implement it:
public class CIMKlarfDefect : IKlarfDefect, IHasKlarfImageList<CIMKlarfImageListInfo>
{
public int TEST { get; set; }
public int DEFECTID { get; set; }
public List<CIMKlarfImageListInfo> KlarfImageList { get; set; } = new List<CIMKlarfImageListInfo>();
}
public class RMTKlarfDefect : IKlarfDefect, IHasKlarfImageList<CIMKlarfImageListInfo>
{
public int TEST { get; set; }
public int DEFECTID { get; set; }
public List<RMTKlarfImageListInfo> KlarfImageList { get; set; } = new List<RMTKlarfImageListInfo>();
}
Then I have this function in another class that tries to read through these classes:
internal static string CreateCIMDefectListString(IEnumerable<IKlarfDefect<IKlarfImageListInfo>> klarfDefectList)
{
StringBuilder defectListString = new StringBuilder();
defectListString.AppendLine("");
foreach (var klarfDefect in klarfDefectList) {
defectListString.Append(klarfDefect.TEST).Append(" ");
defectListString.Append(klarfDefect.DEFECTID).Append(" ");
if (klarfDefect is IHasKlarfImageList<IKlarfImageListInfo> grcKlarfDefect)
{
if (grcKlarfDefect.KlarfImageList.Count == 0)
{
defectListString.Append("N;");
defectListString.AppendLine();
}
}
}
return defectListString.ToString();
}
It compiles but the if statement fails when I am passing in either RMTKlarfDefect or CIMKlarfDefect. Might anyone know why this is?
if klarfDefect is IHasKlarfImageList grcKlarfDefect
fails as in, it doesn't return true which would allow it to process the imagelist
Your if statement says
if (klarfDefect is IHasKlarfImageList<IKlarfImageListInfo> grcKlarfDefect)
But your classes implement
IHasKlarfImageList<CIMKlarfImageListInfo>
So you need to update your if statement accordingly:
if (klarfDefect is IHasKlarfImageList<CIMKlarfImageListInfo> grcKlarfDefect)

How to create instance of nested class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 years ago.
I have a viewmodel and it contains two viewmodel in ReaderBorrowViewModel, I'm not sure it's best practice but it makes sense to me. In GetReaderDetailModel method i got borrows from db. After every borrowed book i tried to get data for ReaderDetailViewModel which contains BookStateModel and BookViewModel.Getting all borrowed books i added to list in ReaderBorrowModel to send it client.I got Object reference not set to an instance of an object while i creating an instance of ReaderBorrowModel. What's my fault ?
public class BookStateViewModel
{
public int BookStateKey { get; set; }
public string Name { get; set; }
}
public class BookViewModel
{
public int BookKey { get; set; }
public string ISBN { get; set; }
public string Name { get; set; }
public string Author { get; set; }
}
public class ReaderBorrowModel
{
public int BorrowKey { get; set; }
public BookViewModel Book { get; set; }
public BookStateViewModel BookState { get; set; }
}
public class ReaderDetailViewModel
{
public MemberViewModel Member { get; set; }
public List<ReaderBorrowModel> Borrows { get; set; }
}
public async Task<ReaderDetailViewModel> GetReaderDetailModel(int memberKey)
{
ReaderDetailViewModel result = new ReaderDetailViewModel();
var borrows= borrowService.SelectIncludeMany(x => x.Member,k=>k.Book, d=>d.BookState).Where(x=>x.MemberKey== memberKey);
var member= borrows.Select(x => x.Member);
try
{
borrows.ToList().ForEach(o =>
{
var borrow = new ReaderBorrowModel
{
BorrowKey = o.BorrowKey,
Book = new BookViewModel
{
BookKey = o.Book.BookKey ,
Name = o.Book.Name ,
ISBN = o.Book.ISBN ,
Author = o.Book.Author.Name
},
BookState = new BookStateViewModel
{
BookState Key = o.BookState Key,
Name= o.BookState.Name
}
};
result.Borrows.Add(odunc);
});
}
catch (Exception ex)
{
throw ex;
}
return result;
}
You have not initialized the property to a new list. Try the below snippet. Once the list is set to a new list, you don't get null reference exception
public class ReaderDetailViewModel
{
public ReaderDetailViewModel() {
Borrows = new List<ReaderBorrowModel>();
}
public MemberViewModel Member { get; set; }
public List<ReaderBorrowModel> Borrows { get; set; }
}
Note
As a good practice, you can always initialize the list / dictionary etc to a new list or new dictionary etc so that you don't run into null reference exceptions.

Prepopulate a Models property [duplicate]

This question already has answers here:
What is the best way to give a C# auto-property an initial value?
(23 answers)
Closed 5 years ago.
What i'm trying to do is create a new model that will have certain features:
public class GenericGoal
{
public int _id { get; set; }
public List<String> Type_of_Goal { get; set; }
public DateTime Date { get; set; }
}
my quick and small question would be, how would I prepopulate the Type_of_goal field?
You could use a constructor for this; could look like this example.
public class GenericGoal
{
public int _id { get; set; }
public List<String> Type_of_Goal { get; set; }
public DateTime Date { get; set; }
public GenericGoal()
{
Type_of_Goal = new List<String>();
}
}
I recommend the initialisation in the constructor because in my opinion it's cleaner and better readable.
You could give the property 'Type_of_Goal' an initial value, if you don't want to have to initialize it every time, or initialize it when no value is set to it.
public class GenericGoal
{
public int _id { get; set; }
public List<String> Type_of_Goal { get; set; } = new List<String>();
public DateTime Date { get; set; }
}
If it is 'NullReferenceException' you are concerned about, check for null's before accessing the 'Type_of_Goal' property, as follow. Note the ? - Known as Null Propagation Operator
genericGoalInstance.Type_of_Goal?.Add("Good Goal");

Categories