C# dynamically set property When Property is a class? [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
Hi i have a Number of Properties and My properties like
public XYZ()
{
xyz = new xyz1();
xyz2 = new xyz2();
}
public xyz1 xyz1 { get; set; }
public xyz2 xyz2 { get; set; }
}
public class xyz1
{
public string fName { get; set; }
public string lnameget; set;}
}
public class xyz2
{
public string city { get; set; }
public string state
}
While i am setting my property on runtime i am getting exception object reference set to null.
XYZ model = new XYZ();
PropertyInfo propertyInfo = model.GetType().GetProperty("fName");
propertyInfo.SetValue(model, Convert.ChangeType(item.InnerText, propertyInfo.PropertyType), null);
Please help me

model has no fName property, but model.xyz1 does.

Related

How to JsonConvert.SerializeObject after object cast? [duplicate]

This question already has answers here:
How to exclude property from Json Serialization
(9 answers)
Closed 5 years ago.
How to JsonConvert.SerializeObject after object cast?
I have two classes like this example, and I want my serialized json to not include the "Id" field.
public class Person : Description
{
public int Id { get; set; }
}
public class Description
{
public string Name { get; set; }
}
Person person = new Person() { Id = 1, Name = "Bill" };
Description description = person;
string jsonDescription = JsonConvert.SerializeObject(description);
Console.WriteLine(jsonDescription);
// {"Id":1,"Name":"Bill"}
I've tried several things like casting with "as" or casting with .Cast() but no luck yet.
Thank you for your suggestions.
Just use the JsonIgnore attribute.
public class Person : Description
{
[JsonIgnore]
public int Id { get; set; }
}

Filling POCO Object with List inside a List [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I´m attempting to fill a POCO object but I get the NullReferenceException - Object reference not set to an instance of an object, at line "objectAreas.position.Add(objectPositions);" I think I'm not initializing well but I don't see my mistake, let's see the code:
POCO OBJECT
public class GenericQuery
{
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
}
public sealed class Positions
{
public int idposition { get; set; }
public string positionname { get; set; }
}
public sealed class QueryAreasPositions
{
public int code { get; set; }
public string response { get; set; }
public List<Areas> areas { get; set; }
}
}
Filling It
GenericQuery.QueryAreasPositions objectAreasPositions = new GenericQuery.QueryAreasPositions();
var query = areaRepository.Get(); //Eager Loading EntityFramework List Object, see the AreaRepository at the end
objectAreasPositions.code = 123;
objectAreasPositions.response = "anything";
foreach (var area in query)
{
GenericQuery.Areas objectAreas = new GenericQuery.Areas();
objectAreas.idarea = area.IdArea;
objectAreas.areaname = area.Name;
foreach (var position in area.Position)
{
GenericQuery.Positions objectPositions = new GenericQuery.Positions();
objectPositions.idposition = position.IdPosition;
objectPositions.positionname = position.Name;
***objectAreas.position.Add(objectPositions);***//HERE
}
objectAreasPositions.areas.Add(objectAreas); //And maybe here
}
AreaRepository
public List<Area> Get()
{
using (var context = new Entities())
{
return context.Area.Include("Position").ToList();
}
}
I would appreciate any help/guide you can give me, Thanks.
You are never initializing objectAreas.position, hence the default value for a List<T> is null.
Since you are trying to call the Add method on a null reference, you are getting a NullReferenceException.
To fix this, you should initialize the property before using it:
objectAreas.position = new List<GenericQuery.Positions>();
Alternatively, you can add this logic on GenericQuery.Areas constructor, which would be more appropriate:
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
public class Areas()
{
positions = new List<Positions>();
}
}
Shouldn't you rather be doing like below. Your position is null cause not yet initialized and thus the said exception.
objectAreas.position = new List<Position>();
objectAreas.position.Add(objectPositions);

Why I am getting null exception when using an Interface [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
public class Blah
{
public bool Whatever { get; set; }
public string WhatYouJustSaid { get; set; }
}
public interface IBlah
{
Blah BlahValues { get; set; }
}
class Class1:IBlah
{
public Blah BlahValues { get; set; }
}
And then for example:
Class1 c1 = new Class1();
c1.BlahValues.WhatYouJustSaid = "nothing";
c1.BlahValues.Whatever = false;
So how should I change my code that BlahValues doesn't get null?
You have to initialize the BlahValues. Using an object initializer, this can be done as below:
Class1 c1 = new Class1()
{
BlahValues = new Blah()
};
As you create the c1 object, the BlahValues get it's default value, which is null. Hence, when you try to assign a value to WhatYouJustSaid and Whatever you get a null reference exception.
use it like this inside the constructor of Class1
public Class1()
{
this.BlahValues = new Blah()
}

why null reference exception in List<decimal> [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
i have a problem, i created an object in C# like this:
public class logis
{
public string codigo { get; set; }
public List<decimal> Necesidades { get; set; }
decimal SumaNecesidades{get;set;}
}
then i do something like this:
logisva logi = new logis();
logi.codigo = oDataReader.GetValue(0).ToString();
logi.Necesidades.Add(0);
But when i execute my code i get a null reference exception error. Object reference not set to an instance of an object. on the last line logi.Necesidades.Add(0);
Any idea why i get this error?
In C# the properties do not initialize/create the List<ofType> object automatically. You need to create the list explicitely:
public class logis
{
public string codigo { get; set; }
public List<decimal> Necesidades { get; set; }
decimal SumaNecesidades{get;set;}
public logis()
{
this.Necesidades = new List<decimal>();
}
}
Another option is to create the list in the getter resp. setter (so to say your own lazy initialization, downside - introduces more code, advantage no need to override every contructor):
public class logis
{
public string codigo { get; set; }
decimal SumaNecesidades{get;set;}
private List<decimal> necesidades = null;
private void initNecesidades()
{
if (this.necesidades == null)
{
this.necesidades = new List<decimal>();
}
}
public List<decimal> Necesidades
{
get
{
this.initNecesidades();
return this.necesidades;
}
set
{
this.initNecesidades();
this.necesidades = value;
}
}
}
Yet another option would be to use the new C# 6.0 features (if it is an option to use/already using the latest .NET Framework version) as already suggested in the comments by #Jcl:
public List<decimal> Necesidades { get; set; } = new List<decimal>()

WCF: Object Reference Not Set To Instance Of a an Object [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a CibilResponse Class that has properties that are of class type (TUEF class). I am trying to assign value to CibilEnquiryEnq.Tuef.Version but i am getting null reference error. Before you mark this question as duplicate let me mention that I have read some of the similar questions and their answers on SO and post which I have initialized tuef in the constructor as you can see in my code. Can you please point out if you can what is it that I am doing wrong?
ICIBIL.cs
[ServiceContract]
public interface ICIBIL
{
[OperationContract]
string InsertCibil(CibilResponse cibilResponse);
[OperationContract]
string GenerateEnquiry(CibilEnquiry testObj);
}
[DataContract]
public class CibilResponse
{
[DataMember]
public string ResponseString { get; set; }
[DataMember]
public string Business { get; set; }
[DataMember]
public string MkrId { get; set; }
}
[DataContract]
public class CibilEnquiry
{
[DataMember]
public TUEF Tuef { get; set; }
public CibilEnquiry()
{
this.Tuef = new TUEF();
}
}
[DataContract]
public class TUEF
{
[DataMember]
public string SegmentTag { get; set; }
[DataMember]
public string Version { get; set; }
[DataMember]
public string MemberReferenceNumber { get; set; }
}
Appication :
CibilWcfService.CIBIL obj = new CibilWcfService.CIBIL();
CibilWcfService.CibilEnquiry CibilEnquiryEnq = new CibilWcfService.CibilEnquiry();
CibilEnquiryEnq.Tuef.Version = "123";// null reference error here
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
Can you try the below. C# is case sensitive.
using CbilFileReader.CibilWcfService;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CIBIL obj = new CIBIL();
CibilEnquiry CibilEnquiryEnq = new CibilEnquiry();
TUEF objtuef = new TUEF();
objtuef.Version = "123";
CibilEnquiryEnq.Tuef = objtuef;
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
}
}
}
This might do the trick for you
CibilWcfService.CIBIL obj = new CibilWcfService.CIBIL();
CibilWcfService.CibilEnquiry CibilEnquiryEnq = new CibilWcfService.CibilEnquiry();
CibilWcfService.CibilEnquiry.Tuef ObjTUEF = new CibilWcfService.CibilEnquiry.Tuef();
ObjTUEF.Version="123";
CibilEnquiryEnq.Tuef = ObjTUEF;
string res = obj.GenerateEnquiry(CibilEnquiryEnq);

Categories

Resources