I am trying to use CsvHelper library to write records (or list<SomeModel>) to CSV, but SomeModel class has some reference types properties that are sometimes null. I am wondering is there a way to print nulls as empty string instead of "null". I can see that CsvWriter.WriteRecords method is virtual so I can extend the class and create a custom implementation of it but there should be an easier way or some confirguration.
You can simply set this attribute
csv.Configuration.UseNewObjectForNullReferenceMembers = true;
it'll simply create a new object if a null reference is found.
In the ctor of the object class, assign empty string as default.
Related
I have a class like this:
class MyClass
{
public MyClass(string s)
{
_s = s;
}
string _s;
}
Now I want this class remember the value of s string the way whenever it's changed in the code instantiated this class, the stored _s value reflects the change.
The obvious way is to create a wrapper class like StringContainer which will have a single property holding a string and pass the instance of this wrapper class instead of just the string (so that both the caller and MyClass instance always work with StringContainer.s, not s directly).
However, it seems a bit heavy solution, I'm curious if anything nicer exists? Maybe there is a built-in C# construct for that? Like 'ref' modifier when you need to pass something by reference in a method call. Maybe some kind of generic type wrapper like Nullable to enable creating such wrappers with less code?
In the end, it's actually not about strings only, it's about passing a pointer instead of just the value for any type, be it string, object, int, etc. For instance:
Create an object in the caller and assign it to a variable
Pass the variable pointing referencing this object to MyClass instance
In the caller, assign another object to the variable
Result: MyClass instance automatically 'sees' the new value of the object
I'd like to take simple public properties and turn them into anonymous accessors, but some of my logic requires the initial values of the accessors/properties be null, can I rely on anonymous accessors to be null if I've not assign them a value?
currently :
public string XML = null; // set XML or XMLPath to turn on XML stuff
public string XMLPath = null;
compared to :
public string XML {get; set;}
public string XMLPath {get; set;}
You don't need to do anything. They are null by default. This is true also for fields. Actually, a automatic property also uses a field and that's why the default value of an automatic property is null (or default(T) to be more precise).
Unassigned auto-implemented properties are defined to start with the default value for their type. So reference types start null.
New class fields are always initialized with nulls (except simple types which are initialized with them default values, like 0 for integer). You do not need to assign the null to them. It all aplies to auto implemented properties and fields in anonymouse object too.
Only method variables are not initialized, but as for them if you'll try to read them without initializing them first you'll get the compiler error first, so you don't need to worry here either.
Conclusion: C# always cares about not accessing uninitialized variables on compile-time, there is no chance that you will access variable that do not have default value assigned on runtime.
Is there a way to get str1 in code ?
[MyAttribute("str1")]
class X {}
The instance of Mono.Cecil.CustomAttribute.Fields is empty.
When using attributes in .NET you are either using the constructor parameters and setting some (named) fields. This is encoded differently in the metadata and ends up separately in Cecil.
the instance of Mono.Cecil.CustomAttribute.Fields is empty
What you're using is looking for fields when the constructor arguments were used for the custom attribute. So what you're looking for is:
type.CustomAttributes[0].ConstructorArguments[0].Value
I am trying to call a class method dynamically depending on a condition. This is how I am doing it
I have three classes implement a single interface
interface IReadFile
{
string DoStuff();
}
The three classes A,B,C implement the interface above.
I am trying to add them to a hashtable with the code below
_HashT.Add("a", new classA());
_HashT.Add("b", new classB());
_HashT.Add("c", new classC());
This compiles fine, but gives a runtime error.{Object reference not set to an instance of an object.}
I was planning to return the correct class to the interface type depending on a parameter that matches the key value. say if I send in a. ClassA is returned to the interface type and the method is called.
IReadFile Obj = (IReadFile )_HashT["a"].GetType();
obj.DoStuff();
How do I correct the part above where the objects need to be added to the hashtable? Or do I need to use a different approach? All the classes are in the same assembly and namespace.
Thanks for your time.
As a guess, you have not instantiated your _HashT object.
You need somewhere in your code (declaration or constructor probably) to instantiate it:
HashTable _HashT = new HashTable();
If you do not do this, _HashT will be null and an attempt to add to it will fail with a NullReferenceException as you have been getting.
It appears you are seeing a NullReferenceException. Based on the limited code you provided I would say it is likely that the _HashT variable is not assigned. It could be possible that the exception is being generated from one of your class constructors as well.
If you use Dictionary<> you can use the following code to add and extract objects from the hashtable.
var hashtable = new Dictionary<IReadFile>();
hashtable.Add("a", new ClassA());
hashtable.Add("b", new ClassB());
hashtable.Add("c", new ClassC());
IReadFile obj = hashtable["a"];
obj.DoStuff();
Following your approach, you do not need to call GetType() on the value you pull out of _HashT. The value should already be an object of type IReadFile.
Why are you calling GetType? The IReadFile object is the thing you are putting in the hash. Casting a Type object into a IReadFile is not going to cast correctly.
I am writing a web service to expose certain pieces of data to one of our third party applications. Their team requires a generic way to retrieve values of fields in our system. I have written a class where the only public members of the class are the values they need. What I would like to do is have them pass an enumerated string that is the name of the member they want to retrieve and if it is a valid name of a public member, return the value of that member. I was messing around with some of the reflection methods in .net but can't quite get the behavior I am looking for. I am trying to write something to recreate the functionality of this pseudo code:
public Object webserviceMethodToReturnValue(Guid guidOfInternalObject, String nameOfProperty)
{
internalObject obj = new internalObject(guid); //my internal company object, which contains all the public members the external company will need
Object returnObject = obj.{nameOfProperty}; //where name of property is evaluated as the name of the member of the internalOject
return returnObject; //returning an object that could be casted appropriately by the caller
}
So that you could call the service like:
String companyName = (String)webserviceMethodToReturnValue(guid, "companyName");
You need to call the GetProperty method, like this:
PropertyInfo property = typeof(InternalObject).GetProperty(nameOfProperty);
return property.GetValue(obj, null);
Beware that it won't be very fast.
To make it faster, you could use expression trees in .Net 3.5 to create statically-typed methods at runtime that return the values.
Reflection!
Yep! you would do this: typeof(InternalObject).GetProperty(nameOfProperty).GetValue(obj,null)