Class with mandatory parameter - c#-3.0

i have some mandatory fields and when calling the constructor of my class i got null reference exception, how prevent this please.
new Part(Partitems["Name"].ToString(), Partitems["Logo"].ToString(), Partitems["Description"].ToString(), Partitems["URL"].ToString()));
MY Class :
public class Part
{
string _Name= string.Empty;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
...
..
EDIT
Here is constructor code
public Part(string Name, string Logo, string Description, string URL)
{
this.Name = Name;
this.Logo = Logo;
this.Description = Description;
this.URL = URL;
}

may be one of this properties
Partitems["Name"], Partitems["Logo"],Partitems["Description"],Partitems["URL"]
is null? Your constructor code will help to understand problem more...

There's nothing in the constructor that could cause a null reference exception, as assigning null to a string property is perfectly valid. So, either your Partitems variable is null, or one of it's properties returns null.
Example for handling both situations:
if (Partitems != null) {
object name = Partitems["Name"] ?? String.Empty;
object logo = Partitems["Logo"] ?? String.Empty;
object description = Partitems["Description"] ?? String.Empty;
object url = Partitems["URL"] ?? String.Empty;
part = new Part(name.ToString(), logo.ToString(), description.ToString(), url.ToString()));
} else {
// Oops, Partitems is null. Better tell the user or log the error...
}
This will replace any null values in the properties with empty strings. However, you might want to handle it as an error situation instead, depending on the situation.

Related

A value of type 'xxx?' can't be returned from a function with return type 'xxx' because 'xxx?' is nullable and 'xxx' isn't

I am learning factory method in dart. However I encounter a problem, which says
A value of type 'Person?' can't be returned from a function with return type 'Person' because 'Person?' is nullable and 'Person' isn't.
3-1.dart:13
Here is my code:
void main(List<String> args) {
Person a = new Person("zarkli");
a.say("hello");
}
class Person{
final name;
static final Map<String, Person> _cache = new Map<String,Person>();
factory Person(String name){
if (_cache.containsKey(name)){
return _cache[name]; // error
} else {
final person = new Person.newPerson(name);
_cache[name] = person;
return person;
}
}
Person.newPerson(this.name);
void say(String content){
print("$name: $content");
}
}
Some maps allow null as a value. For those maps, a lookup using this operator cannot distinguish between a key not being in the map, and the key being there with a null value.
This is from the get operator documentation for map. When you use containsKey it could be the case that the key exists but its value is null.
You can use a local variable to store _cache[name] and check if it's null or not. Dart then can promote that local variable and not give you any errors. So your factory will look like this:
factory Person(String name) {
final cached = _cache[name];
if (cached != null) {
return cached;
} else {
final person = Person.newPerson(name);
_cache[name] = person;
return person;
}
}

Does Entity Framework call property setters with null when rehydrating entities for columns with DB NULL?

I have a string property
public string XYZ
{
get => // do stuff
set => // do stuff which handles null
}
because I'm hoping it will get called....
But will it really?
(EF6.4)
It appears it will. If you implement the property with a backing field it's easy to test this by putting a breakpoint in the setter. EG
private string xyz;
public string XYZ
{
get
{
return xyz;
}
set
{
xyz = value;
}
}
And I think it would have to, as EF does not know whether your entities have a non-standard default value for a property. eg you could write
private string xyz = "none";
public string XYZ
{
get
{
return xyz;
}
set
{
xyz = value;
}
}
And so the hydration code would need to run the setter to get a correct result.

Dart Flutter How to initialize a class method inside of its class?

Here is my class:
class WorldTimeClass {
String flag;
String url;
String time;
String location;
WorldTimeClass({this.flag, this.url, this.time, this.location});
Future<String> getData() async {
try{
Response load = await get('http://worldtimeapi.org/api/timezone/$url');
Map x(){if(load.statusCode == 200){
print(load.statusCode);
Map map = jsonDecode(load.body);
return map;}
else{
print('No Access');
return {1:'NoAccess.'};}
}
Map myMap = x();
String datetime = myMap['utc_datetime'];
String offsetUTC = myMap['utc_offset'];
DateTime dateTimeObjectConvert = DateTime.parse(datetime);
// Below converts the datetime string to a DateTime Object and then converts the UTC Offset to a substring only '01' out of +01:00 and then converts it to an int Object and then adds it to the DateTime Object as a Duration (hours);
dateTimeObjectConvert = dateTimeObjectConvert.add(Duration(hours: int.parse(offsetUTC.substring(1,3))));
return time = dateTimeObjectConvert.toString();
}
catch(e,s){
return 'Could not access time data from API.\nWe are sorry, please try again.\nError occured: $e';
}
}
var myString = getData().then((value) => value);
DateFormat pretty = DateFormat().add_jm().format(myString);
}
How can I access myString and execute it inside my class in order to use the resulting String object to use it inside a second method pretty ?
Also, I need to understand what does the below exception mean?
Only static members can be accessed in initializers.
Only static members can be accessed in initializers.
This basically means that you cannot call methods of a class or access properties of a specific class directly under class declaration.
You are getting the error on those two lines:
var myString = getData().then((value) => value);
DateFormat pretty = DateFormat().add_jm().format(myString);
Therefore create a method that returns a String then all you have to do is to call that method and it will give you the String, and add the code above inside the method:
String getDateFormat(){
var myString = getData().then((value) => value);
return DateFormat().add_jm().format(myString);
}
To access your myString variable you'll have to do one of those things:
Instantiate an WorldTimeClass object and access it using yourWorldClassObject.myString
Make it into in static member by using the static keyword like static var myString. This is what " Only static members can be accessed in initializers. " is all about. You have to create an instance of the class if you want to access it's properties, or make them static to access them without the need to instantiate an object. Simply WorldTimeClass.myString.

How to return an object or struct from a method in MQL?

struct Person {
string FirstName;
string LastName;
};
class Builder {
public:
Person Builder::Build() {
Person person;
person.FirstName = "FirstName";
person.LastName = "LastName";
return person;
};
};
When I compile this it gives me the below error:
'return' - structure have objects and cannot be copied.
I just need to create a struct or class object and return it, I don't want to do any copying.
I tried using & and * combinations but didn't work. I tried with a class instead of struct and it didn't work either.
I also tried with class as shown below:
class Person {
public:
string FirstName;
string LastName;
};
class Builder {
public:
Person* Build() {
Person person;
person.FirstName = "FirstName";
person.LastName = "LastName";
return &person;
};
};
int OnInit()
{
Builder builder;
Person* person = builder.Build();
string firstName = person.FirstName;
return(INIT_SUCCEEDED);
}
And it gives me invalid pointer access when accessing person.FirstName in the OnInit() method at runtime.
Found the answer but how to avoid memory leak? how to destruct the object and its pointer after use?
class cPerson {
public:
string FirstName;
string LastName;
};
class cBuilder {
public:
cPerson* Build() {
cPerson* person = new cPerson();
person.FirstName = "firstname";
return person;
};
};
cBuilder builder;
cPerson* person = builder.Build();
string age = person.FirstName;
You can delete the object by delete(person); and if you are unsure the object is not a null, it is better to check if(CheckPointer(object)==POINTER_DYNAMIC)delete(object);
Overall you should have all such objects as variables with corresponding variable names, or keep them all in a collection and destroy the whole collection at end. You may also create global variable of object (before OnInit, not inside any function) and it is to be deleted at end of program.
Regarding the initial question - you cannot have string inside a struct, only primitives
you should NOT delete static objects - you will get "delete invalid pointer"-message from compiler in print area... therefore the check should be done as Daniel Kniaz answered... but as so as you are creating the object inside the wrapper - you'd better have a check for deletion & delete it in the Destructor of its wrapper (though I doubt, that you really should use here another class for CPerson creation - yuo can create its object in its - CPerson's - Constructor)
First you need a default constructor and copy constructor in your code. second you need to initialize the struct to default value, the struct only allocate space in the memory and not initialize it, so you can end up with cases where a long variable has some weird value like -1823834393939, so always set your struct to default values.
then when you return a class or struct from a function. the copy constructor will be called that copy the values. so if you don't want to return the exact object you've created in your class you don't need to return a reference
struct Person
{
string FirstName;
string LastName;
Person()
{
FirstName = "";
LastName = "";
}
Person(Person &that)
{
FirstName = that.FirstName;
LastName = that.LastName;
}
};
class Builder
{
public:
Person Builder::Build(string argFirstname, string argLastName)
{
Person person;
person.FirstName = argFirstname;
person.LastName = argLastName;
return person;
};
};
void OnStart()
{
Builder b;
Person p = b.Build("Mohammad Hossein", "amri");
Print(p.FirstName + " " + p.LastName);
}
the output will be

How can I return only several Json fields of an inner object with Jackson

I'm using Jackson + spring RestControlles
Lets say I have 3 classes
class Card {
String id;
String pan;
String holder;
String expiry;
}
class CardProfile {
String id;
Card card;
...
}
class Recipient {
String name;
Card card;
...
}
So when I serialize a CardProfile object I want all fields of object card to be percent in result json.
But in case Recipient object , Json has to have only part of object card(For example : pan, holder) .
Is there a way to present Card object in json with different set of fields?
Use of annotations like #JsonIgnore will remove fields from both cases.
Thanks.
Thinking again - is this approach scalable? What if you need something similar again?
Why not rely on inheritance and create a base class and multiple subclasses with attributes you are interested in?
class Card{
// bare min attribute
.....
}
class SubCard1 extends Card{
//add more attribute
.....
}
class SubCard2 extends Card{
//add more attribute
.....
}
Use SubCard1 or SubCard2 based on what you need? Same can be used for other classes. If this is more dynamic - look at design patterns.
when you serialize the object you can keep only the parameter that are interest for you.
I post a simple java code to resolve this stuff you can convert the code in the lenguage that you need.
the following code is prt of the Recipient class which contains two field: String name and Card card
To write the json object:
#Override
public final void toJSON(final OutputStream out) throws IOException {
final JsonGenerator jg = JSON_FACTORY.createGenerator(out);
jg.writeStartObject();
jg.writeFieldName("Recipient");
jg.writeStartObject();
jg.writeNumberField("id",card.getID());
jg.writeStringField("name", name);
jg.writeStringField("pan", card.getPan());
jg.writeStringField("holder", card.getHolder());
jg.writeEndObject();
jg.writeEndObject();
jg.flush();
}
to get the the object from the json:
public static Recipient fromJSON(final InputStream in) throws IOException {
int jId = -1;
String jName = null;
String jHolder = null;
String jPan = null;
//Obtain a new JsonParser to parse Recipient from JSON
final JsonParser jp = JSON_FACTORY.createParser(in);
while (jp.getCurrentToken() != JsonToken.FIELD_NAME || "Recipient".equals(jp.getCurrentName()) == false) {
// there are no more events
if (jp.nextToken() == null) {
throw new IOException("Unable to parse JSON: no employee object found.");
}
}
while (jp.nextToken() != JsonToken.END_OBJECT) {
if (jp.getCurrentToken() == JsonToken.FIELD_NAME) {
switch (jp.getCurrentName()) {
case "id":
jp.nextToken();
jId = jp.getIntValue();
break;
case "name":
jp.nextToken();
jName = jp.getText();
break;
case "pan":
jp.nextToken();
jPan = jp.getText();
break;
case "holder":
jp.nextToken();
jHolder = jp.getText();
break; }
} }
//create new card object, the values not present in the json will set to null
Card card = new Card(jId,null,jPan,jHolder,null);
return new Recipient(jName, card);
}
}
I tried to adapt the code for you but it is just to give you an idea,I hope this will be usefull for you.