System.NullReferenceException: ... in C# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's the code:
foreach (var property in this.allProperties)
{
var propertyItself = element.GetType().GetProperty(property.GetType().Name);
if (propertyItself.PropertyType != typeof(Int32)) // Here I get System.NullReferenceException: Object reference not set to an instance of an object
{ continue; }
if ((int)propertyItself.GetValue(element, null) == 0)
{ return false; }
}
I can't figure this out. If any one can or understand what is going on, please help us! Thanks in advance!!!

The propertyItself variable is null.
That means that this call is somehow incorrect:
element.GetType().GetProperty(property.GetType().Name);
I'm just guessing, but I bet this code property.GetType().Name should be property.ToString() or property.Name if that is an option.
What you're passing in is the name of the Type of the property, not its Name.

Without any debugger info there is no way to give a specific answer to what is wrong.
Try putting
if(propertyIteself!=null && propertyIteslef.PropertyType!=null && propertyItself.PropertyType != typeof(Int32))
{ continue; }
This will null check both items that could possibly be blowing up on that line.
or try this
foreach (var property in this.allProperties)
{
var propertyItself = element.GetType().GetProperty(property.GetType().Name);
if(propertyItself!=null && propertyItself.PropertyType!=null)
{
if (propertyItself.PropertyType != typeof(Int32))
{ continue; }
if ((int)propertyItself.GetValue(element, null) == 0)
{ return false; }
}
}

Related

i am receiving an error while returning `<IEnumerable<RiskValue>`.. ASP.NET [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 1 year ago.
Improve this question
var result = JsonConvert.DeserializeObject<Risks>(jsonData);
var finalResult = result.Value.Where(x => x.ID == 5).ToList();
return finalResult;
I am working on an API that returns <IEnumerable<RiskValue> the deserializing does not cause any error this error is shown when I return the final result, any idea of what causing this?
System.InvalidOperationException: The JSON property name for 'MyProject.Models.RisksValue.ID' collides
with another property.
System.InvalidOperationException: The JSON property name for 'test_1.Models.RisksValue.ID' collides with another property.
at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerPropertyNameConflict(Type type, JsonPropertyInfo jsonPropertyInfo)
Try to set PropertyNameCaseInsensitive to false in your Startup.cs:
services.AddControllers().AddJsonOptions(options => {
options.JsonSerializerOptions.PropertyNamingPolicy = null;
//the importance here..
options.JsonSerializerOptions.PropertyNameCaseInsensitive = false;
});

Should I adjust the value of a property when setting it or when getting it? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Hello guys, please don't be too harsh. I am a beginner.
What is the best practice for and what is the difference b/n the following:
#1
public SodaDateTime DteRegistered
{
get { return DateTimeUtil.NullDateForMaxOrMinDate(this._dteRegistered); }
set
{
if (DateTimeUtil.IsNullDate(value))
{
this._dteRegistered = new SodaDateTime("DteRegistered", this, DateTime.Today);
}
else
{
this._dteRegistered = new SodaDateTime("DteRegistered", this, value);
}
}
}
VS. #2
public SodaDateTime DteRegistered
{
get
{
if (DateTimeUtil.IsNullDate(this._dteRegistered))
{
_dteRegistered = new SodaDateTime("DteRegistered", this, DateTime.Today);
}
return this._dteRegistered;
}
set { _dteRegistered = new SodaDateTime("DteRegistered", this, value); }
}
Microsoft published a Property Design Document which provides the following guidance that I believe is applicable to your question:
✓ DO provide sensible default values for all properties, ensuring that the defaults do not result in a security hole or terribly inefficient code.
✓ DO preserve the previous value if a property setter throws an exception.
X AVOID throwing exceptions from property getters. Property getters should be simple operations and should not have any preconditions. If a getter can throw an exception, it should probably be redesigned to be a method.
Based on the guidance that a property should have a valid default value and that getters should be simple operations, I would suggest that you do validation in the setter. It also might be reasonable to throw an ArgumentOutOfRangeException in the setter if the value passed is not valid, so that the client working with your class understands what's happening
// Provide reasonable default value
private SodaDateTime _dteRegistered =
new SodaDateTime("DteRegistered", this, DateTime.Today);
// Getter is a simple operation without preconditions
public SodaDateTime DteRegistered
{
get { return _dteRegistered; }
set
{
if (value == null)
{
throw new ArgumentOutOfRangeException("value cannot be null");
}
if (DateTimeUtil.IsNullDate(value))
{
throw new ArgumentOutOfRangeException("value cannot have a null date");
// or: value = DateTime.Today;
}
this._dteRegistered = DateTimeUtil.NullDateForMaxOrMinDate(
new SodaDateTime("DteRegistered", this, value));
}
}

copying one objects data to other? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I need to update EF record, in method I have EF object and another new objct which I want to use to update data from. But I m not sure how to copy data from new object to existing one.
Help please.
Here is my code:
public int PostHomeLead(string _lead)
{
try
{
int result = 0;
Lead lead = new Lead();
lead = new JavaScriptSerializer().Deserialize<Lead>(_lead);
//check if lead exist with same session id, if so update it other wise add new.
Lead existingLead = new Lead();
existingLead = db2.HomeLoanCustRepo.GetByID(lead.Lead_id);
if (existingLead == null)
{
db2.HomeLoanCustRepo.Insert(lead);
db2.Save();
result = 1;
}
else
{
db2.HomeLoanCustRepo.Update(lead);
db2.Save();
result = 1;
}
return result;
}
catch(Exception ex)
{
throw ex;
}
}
Either map the properties manually:
existingLead.Foo = deserializedLead.Foo;
existingLead.Bar = deserializedLead.Bar;
existingLead.Baz = deserializedLead.Baz;
Or use a library that does this, like AutoMapper.
As for your comment, creating a deep copy is what you seem to be after. Note this allows for overposting or mass assignment when you don't verify which properties may be updated. You'll need to Attach() the cloned object when using cloning or mapping, as it will not be the same object as returned by GetByID(), so Entity Framework's change tracker won't recognize it.

How can you create a c# dependent variable? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to create a c# method that can be reused multiple times,but depending on the condition of the variable type, i would like to be able to construct the name of a text field.
For example, if type="TY" then I would like to call
if ((String)this.TYIdlabelChange.Value == null)
However, if type="CA", then I would like to call
if ((String)this.CAIdlabelChange.Value == null)
Other examples:
if ((String)this.DIIdlabelChange.Value == null)
if ((String)this.LOIdlabelChange.Value == null)
if ((String)this.REIdlabelChange.Value == null)
etc...
Any ideas?
Thank you!
You need use Page.FindControl, something like this
var tb = FindControl(type+"IdlabelChange") as Textbox;
if(tb != null && tb.Value != null){
....
}

C# get name of object as string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an object named 'Account' and the following code:
Account objAcc = new Account();
objAcc.Name = "Test";
The above is working fine, as expected. I now have a list of values as follows:
string props = "Name,Address,Telephone";
Now, what I want to do is see if "Name" exists in that list. I only have the object to use though (hard coding a case statement etc isn't possible as the object is dynamic), so from objAcc.Name, I somehow need to get "Name" from that, and then see if it's in the list.
Thanks in advance, I hope it's clear enough,
Dave
You can use reflection, by doing that :
var properties = objAcc.GetType().GetProperties();
foreach(var property in properties)
{
if(props.Contains(property.Name))
{
//Do you stuff
}
}
string test = objAcc.GetType().GetProperty("Name") == null ? "" : objAcc.GetType().GetProperty("Name").Name;
bool result = "Name,Address,Telephone".Split(',').Contains(test);
You may use the following method if you like:
public bool PropertyExists<T>(string propertyName, IEnumerable<string> propertyList,T obj)
{
string test = obj.GetType().GetProperty(propertyName) == null ? "" : obj.GetType().GetProperty(propertyName).Name;
bool result = propertyList.Contains(test);
return result;
}
Giannis

Categories

Resources