In this event handler:
public static void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
DateTimeOffset timeStampUTC = args.Position.Coordinate.Timestamp.ToUniversalTime();
DateTimeOffset timeStampLocal = timeStampUTC.LocalDateTime;
DateTimeOffset dateTimeStampUTC = timeStampUTC.DateTime;
RecordLocation(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude,
args.Position.CivicAddress.City, args.Position.CivicAddress.State, dateTimeStampUTC, timeStampLocal);
}
...I'm getting a Null Reference Exception because args.Position.CivicAddress is null (the rest of the args passed to RecordLocation() are valid). I reckon sometimes Position will be null, and sometimes it won't. What can I do to let the times when no City or State is found pass through unabated? I tried to make those strings in RecordLocation()'s definition nullable, but that won't compile.
Do I need to check CivicAddress for null and create an overloaded version of my RecordLocation() method, or is there another way to handle this?
What can I do to let the times when no City or State is found pass through unabated?
You just need to check it. For example:
if (args.Position != null && args.Position.CivicAddress != null)
{
// Now you can use args.Position.CivicAddress.State safely
}
If you want to do lots of things with args.Position, you quite possibly want one "outer" if statement - quite possibly with a local variable to simplify things:
var position = args.Position;
if (position != null)
{
if (position.CivicAddress != null)
{
// Use properties of position.CivicAddress
}
// Assuming Coordinate is nullable to start with, of course...
if (position.Coordinate != null)
{
// ...
}
}
Related
I'm trying to do smth like
Im trying to assign property on an object if this object is not null.
but standard form of non-null invocation does not work for assignment like this
socket?.Blocking = false
what I'm trying to do is shorten this if possible:
if(socket != null) socket.Blocking = false
This would be a great feature
b?.c = "bob"
Though, it's flawed when it comes to compound assignments. Consider this
a.b?.c = "bob"
What should it do on null?
Personally, I think it should just ignore the parents. But alas, the powers that be have probably made the right decision to disallow this because of inconsistency with the other use cases of null conditional.
Note : you could roll your own an extension method, though it's not very satisfying, and would probably fail my code reviews just on abstractness and readability.
a?b.NullConditional(x => x.c = "bob");
You are left with
if(a?.b != null) a.b.c = "bob"
or in your case
if(socket != null) socket.Blocking = false
or to write a dedicated extension method for this use case.
I think the only way would be to use an extension method, so you could write:
socket?.SetBlocking(false);
You can create the extension method like this:
public static class SocketExtensions
{
public static void SetBlocking(this Socket socket, bool blocking)
{
if (socket != null) socket.Blocking = blocking;
}
}
So I know why I have a null reference exception in this case. My question is how I avoid it given this specific use.
I have a function interpreting JSON data like so:
public IActionResult SendLine([FromBody] User data) {
if (_assets.GetPropertyByName(data.Properties.PropertyName) == null) {
_assets.AddProperty(new Property {
IsToggle = data.Properties.IsToggle,
Order = data.Propertis.Order,
Type = data.Properties.Type,
PropertyName = data.Properties.PropertyName
});
}
_assets.AddRow(data);
return Json(data);
}
The problem is that the Property class can have null values like so:
{
properties: {
isToggle: false,
order: 0,
type: null,
propertyName: "Test"
},
....
}
So I get why it throws the exception that "properties" is null since it has a null value. However this is as intended. How do I check to see if the propertyName is null without it throwing that error?
EDIT:
I'm not sure how null conditionals would help this case. If I put it here
if (_assets.GetPropertyByName(data.Properties?.PropertyName) == null)
it will evaluate to null improperly.
Edit: Updated my answer after realizing this is probably closer to what you need (?):
If the if-clause is where your exception is thrown, just split it up a little more:
var propName = data?.Properties?.PropertyName;
var isPropNameFound = !string.IsNullOrEmpty(propName);
var prop = isPropNameFound ? _assets.GetPropertyByName(propName) : null;
if (isPropNameFound && (prop == null))
{
// Add new property if name was given, and it
// was not found to already have been added?
}
That should ensure propName is null if either data.Properties or data.Properties.PropertyName is null, and do so without throwing a NullReferenceException.
After that, it will run the logic in the if block only if propName had a value, and if _assets.GetPropertyByName(propName) did not return anything.
Well, I need to repeat same code for many properties.
I've seen examples taking Action delegates, but they don't fit quite well here.
I want something like this: (see explanation below)
Dictionary<Property, object> PropertyCorrectValues;
public bool CheckValue(Property P) { return P.Value == PropertyCorrectValues[P]; }
public void DoCorrection(Property P) { P.Value = PropertyCorrectValues[P]; }
.
I want to have a dictionary containing many properties and their respective "correct" values. (I know it's not well declared, but that's the idea). Properties are not necessarely inside my class, some of them are in objects of different assemblies.
A method bool CheckValue(Property). This method must access the actual value of the property and compare to the correct value.
And a method a void DoCorrection(Property). This one sets the property value to the correct value.
Remember I have many of those properties, I wouldn't like to call the methods by hand for each property. I'd rather iterate through the dicionary in a foreach statement.
So, the main question is in the title.
I've tried the by ref, but properties don't accept that.
Am I obligated to use reflection??? Or is there another option (if I need, reflection answer will be accepted as well).
Is there anyway I can make a dictionary with pointers in C#? Or some kind of assignment that changes the value of variable's target instead of changing the target to another value?
Thanks for the help.
You can do this using reflection. Get a list of the properties on the object of interest with typeof(Foo).GetProperties(). Your PropertyCorrectValues property can have type IDictionary<PropertyInfo, object>. Then use the GetValue and SetValue methods on PropertyInfo to perform the desired operations:
public bool CheckProperty(object myObjectToBeChecked, PropertyInfo p)
{
return p.GetValue(myObjectToBeChecked, null).Equals(PropertyCorrectValues[p]);
}
public void DoCorrection(object myObjectToBeCorrected, PropertyInfo p)
{
p.SetValue(myObjectToBeCorrected, PropertyCorrectValues[p]);
}
In addition to Ben's code I'd like to contribute the following code fragment:
Dictionary<string,object> PropertyCorrectValues = new Dictionary<string,object>();
PropertyCorrectValues["UserName"] = "Pete"; // propertyName
PropertyCorrectValues["SomeClass.AccountData"] = "XYZ"; // className.propertyName
public void CheckAndCorrectProperties(object obj) {
if (obj == null) { return; }
// find all properties for given object that need to be checked
var checkableProps = from props
in obj.GetType().GetProperties()
from corr in PropertyCorrectValues
where (corr.Key.Contains(".") == false && props.Name == corr.Key) // propertyName
|| (corr.Key.Contains(".") == true && corr.Key.StartsWith(props.DeclaringType.Name + ".") && corr.Key.EndsWith("." + props.Name)) // className.propertyName
select new { Property = props, Key = corr.Key };
foreach (var pInfo in checkableProps) {
object propValue = pInfo.Property.GetValue(obj, null);
object expectedValue = PropertyCorrectValues[pInfo.Key];
// checking for equal value
if (((propValue == null) && (expectedValue != null)) || (propValue.Equals(expectedValue) == false)) {
// setting value
pInfo.Property.SetValue(obj, expectedValue, null);
}
}
}
When using this "automatic" value correction you might also consider:
You cannot create a PropertyInfo object just by knowing the property name and independently of the declaring class; that's why I chose string for the key.
When using the same property name in different classes then you might need to change the code that is doing the actual assignment because the type between the correct value and the property type might differ.
Using the same property name in different classes will always perform the same check (see point above), so you might need a syntax for property names to restrict it to a specific class (simple dot notation, doesn't work for namespaces or inner classes, but might be extended to do so)
If needed you can replace the "check" and "assign" part with separate method calls, but it might be done inside the code block as stated in my example code.
I want to check that session is null or empty i.e. some thing like this:
if(Session["emp_num"] != null)
{
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
}
Or just
if(Session["emp_num"] != null)
{
// The code
}
because sometimes when i check only with:
if (!string.IsNullOrEmpty(Session["emp_num"].ToString()))
{
//The code
}
I face the following exception:
Null Reference exception
Use this if the session variable emp_num will store a string:
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//The code
}
If it doesn't store a string, but some other type, you should just check for null before accessing the value, as in your second example.
if (HttpContext.Current.Session["emp_num"] != null)
{
// code if session is not null
}
if at all above fails.
You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.
I'd go with your first example - but you could make it slightly more "elegant".
There are a couple of ways, but the ones that springs to mind are:
if (Session["emp_num"] is string)
{
}
or
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
}
This will return null if the variable doesn't exist or isn't a string.
You should first check if Session["emp_num"] exists in the session.
You can ask the session object if its indexer has the emp_num value or use string.IsNullOrEmpty(Session["emp_num"])
If It is simple Session you can apply NULL Check directly Session["emp_num"] != null
But if it's a session of a list Item then You need to apply any one of the following option
Option 1:
if (((List<int>)(Session["emp_num"])) != null && (List<int>)Session["emp_num"])).Count > 0)
{
//Your Logic here
}
Option 2:
List<int> val= Session["emp_num"] as List<int>; //Get the value from Session.
if (val.FirstOrDefault() != null)
{
//Your Logic here
}
Check if the session is empty or not in C# MVC Version Lower than 5.
if (!string.IsNullOrEmpty(Session["emp_num"] as string))
{
//cast it and use it
//business logic
}
Check if the session is empty or not in C# MVC Version Above 5.
if(Session["emp_num"] != null)
{
//cast it and use it
//business logic
}
How do I determine if an object reference is null in C# w/o throwing an exception if it is null?
i.e. If I have a class reference being passed in and I don't know if it is null or not.
testing against null will never* throw an exception
void DoSomething( MyClass value )
{
if( value != null )
{
value.Method();
}
}
* never as in should never. As #Ilya Ryzhenkov points out, an incorrect implementation of the != operator for MyClass could throw an exception. Fortunately Greg Beech has a good blog post on implementing object equality in .NET.
What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block:
void DoSomething( MyClass value )
{
if ( value == null ) return;
// I might throw an ArgumentNullException here, instead
value.Method();
}
Note, that having operator != defined on MyClass would probably lead do different result of a check and NullReferenceException later on. To be absolutely sure, use object.ReferenceEquals(value, null)
if(p != null)
{
DoWork(p);
}
Also, the 'as' keyword is helpful if you want to detect if a class is of the right type and use it all at once.
IExample e = p as IExample;
if(e != null)
DoWork(e);
In the above example if you were to cast e like (IExample)e it will throw an exception if e does not implement IExapmle. If you use 'as' and e doesn't implement IExample e will simply be null.
If you look in the majority of the .NET framework source code you will see they put checks like this at the top of their functions.
public void DoSomething(Object myParam)
{
if (myParam == null) throw new ArgumentNullException("myParam");
// Carry on
}
With C# 6.0 this is much more elegant; you can do it in one line :-)
value?.Method();
If "value" is null, nothing will happen - and no exception.
It's nit picky, but I always code these like ...
if (null == obj) {
obj = new Obj();
}
instead of
if (obj == null) {
obj = new Obj();
}
to avoid accidently writing
if (obj = null) {
obj = new Obj();
}
because
if (null = obj) {
obj = new Obj();
}
will give you a compiler error
Or if you are using value types you can read about nullable types: http://www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx
(YourObject != Null)
you can compare to null?
If it's null instead of throwing an exception you can initialize your object. You can use the Null Pattern.
I have in the application's xaml.cs application derivative definition:
private SortedList myList;
And I want to be able to re-use my constructors. So I needed:
if ( myList == null)
myList = new SortedList();
Thanks Robert!