How do I make this property nullable? - c#

I have this line in C#, where incoming.icon is a property of a custom model, and dataItem.Icon is the property of a custom entity.
dataItem.Icon = incoming.icon;
The compiler complains because incoming.icon is nullable but dataItem.Icon isn't. Here is the dataItem 'Icon' property definition in the entity:
public Guid Icon {
get {
return ValidationHelper.GetGuid(GetValue("Icon"), Guid.Empty);
}
set {
SetValue("Icon", value);
}
}
How do I make this property nullable in order to fix the error?

Like this:
public Guid? Icon
{
get
{
return (Guid?)ValidationHelper.GetGuid(GetValue("Icon"), Guid.Empty);
}
set
{
SetValue("Icon", value.GetValueOrDefault());
}
}

Nullable is the struct that you're looking for.
public Nullable<Guid> Icon
This can be written in shorthand like so:
public Guid? Icon
If your design is that you don't want null values being set on dataItem.icon, then you might want to check incoming.icon and only get it's value if it exists instead. Like this:
if (incoming.icon.HasValue)
dataItem.Icon = incoming.icon.Value;

Related

What does the following ambiguity errors mean?

Researched this error and some have said it's a bug but when I used some of their suggestions it didn't fix the problem. What should I do?
**Code
/// Indicates if the profiles has been added.
public Boolean _isNew
{
get { return _isNew; }
set { _isNew = value; }
}
/// Indicates if any of the fields in the class have been modified
public Boolean _isDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
//Gets and Sets delimiterChar
public Char _delimiterChar
{
get { return _delimiterChar; }
set { _delimiterChar = value;}
}
Error**
Ambiguity between 'ConsoleApplication3.ProfileClass.isNew'and 'ConsoleApplication3.ProfileClass.isNew
Ambiguity between 'ConsoleApplication3.ProfileClass.isDirty'and 'ConsoleApplication3.ProfileClass.isDirty
Ambiguity between 'ConsoleApplication3.ProfileClass._delimiterChar'and 'ConsoleApplication3.ProfileClass._delimiterChar
The code you have posted will cause recursion and eventual stackoverflow. You're trying to set property inside the property setter. You either need a backing field or automatic properties to achieve what you're doing. Something like:
private bool _isNew;
public Boolean IsNew
{
get { return _isNew; }
set { _isNew = value; }
}
or
public Boolean IsNew {get; set;}
In C#, if you specify what you are getting and setting, you cannot use the same name as the property (self-reference issue). As of now, you are attempting to get and set a property to itself, which is not valid. Also a heads up about naming conventions, your public properties should not begin with an underscore, but should follow capital camel casing.
There are two answers to this, both equally valid depending on what you need to do.
METHOD 1: If you take out what it is getting and setting, C# can figure out that there is an implied field that is referenced by the IsNew property. This is essentially shorthand for METHOD 2.
public bool IsNew { get; set; } // shorthand way of creating a property
METHOD 2: Specify a field to get and set.
private bool _isNew; // the field
public bool IsNew { get => _isNew; set => _isNew = value; } // this is the property controlling access to _isNew
Read more information here: Shorthand Accessors and Mutators
Essentially, Use METHOD 1 by default if you don't need to perform any additional operations. However, if you need to provide additional functionality when getting or setting, then use METHOD 2 (I.E. look up the MVVM Pattern for an example https://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/)

How to add and use null value in Enum?

See below enum contains two members: Test and Production
public enum OTA_HotelInvCountNotifRQTarget
{
Test,
Production,
}
I'm looking for the way to add and use Null value in above enum from code like :
inv.Target = OTA_HotelInvCountNotifRQTarget.Null; // Not allowed
Update:
I do not want to add extra NULL in above enum, I want to make this dynamic because the above enum is auto generated. and should be remain same.
Is there a way to achieve this in a method itself i.e without creating any Class or adding extra Enum value in enum?
like : inv.Target = OTA_HotelInvCountNotifRQTarget.Null;
How can I do this?
The underlining values of an enum are int which can't be assigned to null.
If you still want to do so:
Add Null as an option to the enum:
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
Have your target a Nullable type:
Nullable<OTA_HotelInvCountNotifRQTarget> t = null;
//Or in a cleaner way:
OTA_HotelInvCountNotifRQTarget? t = null;
//And in your class:
public class YourType
{
public OTA_HotelInvCountNotifRQTarget? Target { get; set; }
}
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
also answewred here
How to set enum to null
Enum is enum. It value type and you can use
Nullable<OTA_HotelInvCountNotifRQTarget> or OTA_HotelInvCountNotifRQTarget? for represent "not set statement"
but if you still want user null as enum value try
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
Or using the "?" Operator for the variable:
public OTA_HotelInvCountNotifRQTarget? Target;
You have to change the assignment to:
inv.Target = null;

Auto-implemented properties and additional function

Is there a way to do something like this in C#:
public class Class2 {
public string PropertyName1 { get
{
return this; //i mean "PropertyName1"
}
set {
this = value;
DoAdditionalFunction();
}
}
Because I need to call additional function in the "set" I need to have an extra private field like
private string _propertyName1;
public string PropertyName1 { get
{
return _propertyName1;
}
set {
_propertyName1= value;
DoAdditionalFunction();
}
I don't want to use additional property like _propertyName1. Is there a way to accomplish this or any best practices?
No - if you need any behaviour other than the most trivial "set a field, return the field value", you need to write "full" properties. Automatically implemented properties are only a shorthand for trivial properties.
Note that you haven't really got an "extra" private field, in terms of the actual contents of an object - it's just that you're explicitly declaring the private field instead of letting the compiler do it for you as part of the automatically implemented property.
(It's not clear what your first property is trying to do - setting this in a class is invalid, and you can't return this from a property of type string unless you've got a conversion to string...)

what is the automatic variable name of an auto-implemented properties

I'm trying to do this:
public string LangofUser
{
get
{
return string.IsNullOrEmpty("how to get value?") ? "English" : "how to get value?";
}
set;
}
do I have to do this?
string _LangofUser
public string LangofUser
{
get
{
return string.IsNullOrEmpty(_LangofUser) ? "English" : _LangofUser;
}
set { _LangofUser = value};
}
This mixing of auto-implement and not-auto-implemented properties in C# is not possible. A property must be fully auto-implemented or a normal property.
Note: Even with a fully auto-implemented property there is no way to reference the backing field from C# source in a strongly typed manner. It is possible via reflection but that's depending on implementation details of the compiler.
As others have said, don't try to mix automatic and regular properties. Just write a regular property.
If you want to know what secret names we generate behind the scenes for hidden compiler magic, see
Where to learn about VS debugger 'magic names'
but do not rely on that; it can change at any time at our whim.
If you provide your own implementation of the property, it's not automatic any more. So yes, you need to do create the instance.
Check this question
What's the difference between encapsulating a private member as a property and defining a property without a private member?
If you want to keep the automatic property and still have a default value, why don't you initialize it in your constructor?
public class MyClass
{
public MyClass() { LangOfUser = "English"; }
public string LangOfUser { get; set; }
}
Since C# 6, you can also set a default value for a property as follows:
public class MyClass
{
public string LangOfUser { get; set; } = "English";
}

Default value for bool in c#

public bool PrepaymentCalculating { get; set; }
So I declare a variable on one of my classes like that. I want this to default to 'null' and not false. Would I just need to make this a nullable boolean? Or is there a better way to do this?
Would I just need to make this a nullable boolean?
Yes.
Or is there a better way to do this?
No.
You can achieve this with
public bool? PrepaymentCalculating { get; set; }
try
public bool? PrepaymentCalculating { get; set; }
Here's a post on Nullable Types
public bool? PrepaymentCalculating { get; set; }
will make it nullable. Read about it here
If you want it to be null then you need to make it a nullable type.
Like everyone else said, but I thought I'd add, what's your purpose here? It's not often that I want to expose a nullable bool, since this means that everything that uses this property must account for a possible null value.
But sometimes I want to know if it's been initialized or not in a given context, and if not, then use a value from somewhere else (e.g. to cascade property values). In this case you might want to use a pattern like this:
public bool PrepaymentCalculating {
get {
if (_PrepaymentCalculating != null ) {
return (bool)_PrepaymentCalculating;
} else {
return somethingElse; // bool
}
}
set {
_PrepaymentCalculating = value;
}
} protected bool? _PrepaymentCalculating =null;
bool can't be null. The default is probably false (but don't quote me on that).
If you want it to be null, then yes you have to declare it as nullable.

Categories