I want to implement class i.e. we have String class in .Net. In that, if you check when we code....
C#:
String strString = "Value-12346- .";
String[] strArray = strString.Substring(0, strString.Length - 1).TrimEnd().ToUpper().Split("-".ToCharArray());
in this example if you check we are calling multiple functions of String Class, over each function i.e over Substring function TrimEnd is called and over TrimEnd Split function is called. I would like to implement similar. Please help me out.
Many Thanks!!!
Make sure every method returns an object of the same type (or the type you want) and then you can call the methods on the object like that ( cascade or chain). Each of the above method in the string example returns a new string ( note that strings are immutable here ), so you can apply the string functions again and so on.
On a related note, see how Fluent Interface works. The C# example showing non-fluent and fluent API is a good example: http://en.wikipedia.org/wiki/Fluent_interface
public IConfigurationFluent SetColor(string newColor)
{
this.color = newColor;
return this;
}
As manojlds pointed out above, you achieve that by making your class' member methods return the type of their owner class. Now, in particular, the String's methods return a new string instance every time (instead of "modifying" the source and returning it), so you might want in your methods to create a deep copy of "this" and then made any changes to the new object and return it. Not only that, but the String class is immutable.
Sorry for being too detailed.
Related
I'm trying to make a user-friendly debug framework where users can create more debug variables as easily as possible.
I need to cast an object to the return type of my property/method (bool, int, whatever), without knowing what that return type is.
tldr: How can I return a non-generic type (in this example bool) from
public bool MyGetSetProperty {
get {
object obj = new object();
return (bool)obj;
}
}
WITHOUT specifying "return (bool)"? So something like
return (GenericThingHereThatPassesAsBool)obj;
or
return obj as MyGetSetPropertyReturnType;
----------
Detail:
I want users to be able to create new properties in this class as easily as possible - basically copying+pasting the whole code block below, and only replacing "SerializeAll" with their variable name, and the type declaration "bool" with the type they want on the field/property declarations.
In my getter, I have a couple separate checks to see if the entire debug system is enabled. If not, it returns a default value for the given variable.
[Tooltip ("Serialize ALL XML output fields?"), SerializeField]
private bool debugSerializeAll = false;
/// <summary>
/// Serialize ALL XML output fields?
/// </summary>
[DebugValue, DebugDefault (true)]
public bool SerializeAll {
get {
if (!classEnabled || !debug.debugEnabled)
return (bool)GetDefaultValue (MethodBase.GetCurrentMethod ());
return debugSerializeAll;
}
set { debugSerializeAll = value; }
}
The thing is, I can't return "default" because the default value can be overridden - see the "DebugDefault" attribute where the "default" value for this bool is actually "true", at least as far as my debug system is concerned. The method "GetDefaultValue" accommodates for that, and it returns an object that could be a string, int, bool, anything.
I'm already doing funky reflection stuff to access the MethodInfo, PropertyInfo, etc of the getter and property SerializeAll. I just can't figure out how to not have to also specify the (bool) cast on the return. Again, the goal is as little human editing as possible.
Thank you!
You should be able to do this with a cast to dynamic.
return (dynamic)GetDefaultValue (MethodBase.GetCurrentMethod ());
Bear in mind that the compiler isn't actually making this into a cast to bool. Rather, this makes the compiler ignore compile-time type-safety, and instead the program will use reflection at runtime to figure out the best way to take the value returned from GetDefaultValue and turn it into what it needs to be.
I want users to be able to create new properties in this class as easily as possible...
This is a good principle.
... basically copying+pasting the whole code block below, and only replacing "SerializeAll" with their variable name, and the type declaration "bool" with the type they want on the field/property declarations.
That totally breaks the principle you just mentioned, and results in a bunch of boilerplate code and other code smells.
In theory, you could probably create a Fody Weaver or something to add this boilerplate code upon compilation. But that's probably more work than it's worth.
I would hazard a guess that this is an "XY Problem", where you're asking how to achieve the solution that you've imagined, rather than asking how to solve the problem you're actually facing.
Why should every property in your class return a completely different value if certain private fields are set a certain way? This sounds like a big Separation of Concerns problem, where you're tasking your class with doing two completely different things. I strongly suggest you find another way to solve the problem you're trying to solve. For example, when code tries to get an instance of your class, it could go through a method that checks the classEnabled and debug.debugEnabled concepts (which probably belong in a different class), and returns an instance with the properties all set to their defaults.
Please Link click here -> How to cast Object to boolean?
or
I think you need to study for Generic class
Check if a class is derived from a generic class
It's possible to make a extension method for Object but not being able to use it on any derived class?
What a want is some general utilities to convert objects to certain types handling common exceptions. Ej. method for converting object to string but changing null to empty string and trimming white spaces.
object obj = ...
// I want to use de the method when the object is 'casted' as 'object':
string strValue = obj.ToStringTrim();
// But not be able to use it in any subclass. Ej. en this string:
strValue.ToStringTrim();
I know this is a tricky syntactic sugar and I supose the answer will be negative, and I should make a custom utility class for this kind of conversions, but just curious if it's possible...
EDIT
I know this is against inheritance, but I just wanted a hack, syntactic sugar or whatever... And already exists some in C# ;). And, why is this an issue? Well, it's not really an issue, but I don't want to have so much bloat on the autocomplete
No, that's not possible because that's not how inheritance works. A string is an Object. Period!
But why is that an issue? Don't use this extension with a string if you don't want.
However, the extension method could be implemented as:
public static string ToStringTrim(this Object obj)
{
return obj?.ToString().Trim() ?? "";
}
If obj is already a string then this is a no-op because String.ToString is implemented as return this.
For the class below :
class A
{
private List<int> intList;
private List<bool> boolList;
public InitializeClass()
{
intList = new List<int>();
}
}
I want to use reflection to write a linter/post compiler of sorts, to check if a certain method really have any assignment to the class' fields or not. The purpose is to automatically check my own errors. The class cannot use constructor, so I need to call InitializeClass() manually.
I have MethodInfo method and all fields of class FieldInfo[] fields that I wanted to check already but have no idea how to go from here. From the example above, it should be able to detect that I haven't assign anything to boolList in the method body.
I ended up reading the code file directly using regular expression.
The file has some constraint, that is it can contains unlimited methods but each method cannot contain any brackets. (No if, etc.)
Then I use "({)(.*)(})" and choose the 2nd group to eliminate class's bracket, then from that I used "{(.*?)}" and iterate through matches for each method's body. (I don't care about method's name actually, I want to check the entire file) After that I read the method's content line by line and split things with characters like '=' or '.'
I have a C# class that does some parsing of XML passed in to its one public method. The idea is that the method pulls info out of the XML, creates objects and sets up collections of them in public properties...
public class XmlParser {
public List<Customer> Customers { get; set; }
public void ProcessXml(string xml) {
XElement data = XElement.Parse(xml);
CreateEntities(Customers, data);
// do other stuff...
}
}
This way, we can do things like this in the calling code...
XmlParser xp = new XmlParser();
xp.ProcessXml(xml);
// do something with xp.Customers
I am trying to write a private generic method in the parser class, which would be used by the ProcessXml() method, and save me writing boilerplate code over and over again. The beginning of this method looks like this (other parameters missed out for clarity)...
private void CreateEntities<T>(List<T> collection, XElement data) {
if (collection == null) {
collection = new List<T>();
}
// process the XElement passed in, and add objects to the collection
}
I'm trying to use it like this...
CreateEntities(Customers, data);
...where the other parameters allow the compiler to know the generic type, and allow the method to know which entities to create etc.
However, the problem I have is that whilst the method itself works fine, and the collection variable is populated correctly, the public Customers property remains null.
I thought that passing a reference type, such as a List<> to a method allowed the method to modify the type, and have those changes seen outside the method, like in the answer from recursive in this SO post (I know that's a Dictionary, but I would have thought the principle would be the same).
Howcome my method can set collection to a new List<>, but Customers (which is the same object) remains null?
Update: Sigh, I ought to learn to read error messages!
Before I posted my question, I had tried passing the collection by ref, and it gave me compiler errors. I obviously didn't pay enough attention to the messages before moving on to plan B.
Having read the replies here, I tried ref again, and spotted that the compiler error was because I was trying to pass a public property by ref, which is not allowed. I changed the property from an automatic one to one with a backing field, passed the backing field by ref and it all works fine!
I thought that passing a reference type, such as a List<> to a method allowed the method to modify the type, and have those changes seen outside the method
You're getting confused with passing a parameter by reference (using the ref modifier), and passing a reference by value.
When you pass the value of a reference type (e.g. List<Customer>) to a method, you're still passing that argument by value by default. You can change the contents of the object that the variable's value refers to, but you can't change which object the original argument referred to, which is what you're trying to do.
Think about it like this... if I hand someone a piece of paper with my home address on, then they can do two things:
They can go to my house and paint my front door red
They can cross out my address and write a different address on the piece of paper
I will be able to see the result of the first action - it's changing something about the house itself. I won't be able to see the result of the second action, because it's just changing what's on the piece of paper... which is just a copy of what I know to be my home address.
For more details, refer to my article on parameter passing in C#.
To fix your problem, I would just change your CreateEntities method to return a list, rather than accepting one:
private List<T> CreateEntities<T>(XElement data)
{
var list = new List<T>();
// Populate the list...
return list;
}
If the caller wants to add those to an existing list, they can do so easily.
I think you missing the passing reference type by using ref. For more information ref (C# Reference)
I have seen methods passed as parameters in some examples. If I can call one method from another method, why should I pass method as a parameter? What is the purpose behind this design?
Calling one method from another
Passing method as parameter using delegate or Action
Passing in a method as a parameter can be used to prevent dependencies and coupling. Let's take a look at how this can be used for the Strategy pattern:
Let's say we have a method PrintReport, which prints a given list of items, which might be sorted by Name or by Type, based on a parameter. This is the naive approach:
public void PrintReport (List<Item> data, SortOrder sortBy)
{
List<Item> sortedItems;
switch (sortBy)
{
case SortOrder.Name: sortedItems = SortByName(data); break;
case SortOrder.Type: sortedItems = SortByType(data); break;
}
Print(sortedItems);
}
It's simple but it works. But what happens when we want to add a new sort order? We need to update the SortOrder enum, go into PrintReport and add a new case and call the new SortByWhatever method.
But if we passed in a method as a parameter, our PrintReport can be simpler and not care about the sort implementation:
public void PrintReport (List<Item> data, Func<List<Item>, List<Item>> sorter)
{
List<Item> sortedItems = sorter(data);
Print(sortedItems);
}
Now the sorting function can be defined anyway, possibly even in a different assembly that PrintReport isn't even aware of. It can be a lambda function or an anonymous method defined ad-hoc. But in all cases, our method will receive the delegate, use it to sort, and then print the report.
Here's a usage example. At first it looks like we merely moved the switch/case outside of the function, which is important enough since it allows different callers to have different logic. But watch for the third case.
public void HandleData()
{
switch (ReportItemOrder)
{
case SortOrder.Name: PrintReport(data, SortByName); break;
case SortOrder.Type: PrintReport(data, SortByType); break;
case SortOrder.Whatever:
Func<List<Item>, List<Item>> customSort = (items) => /* do something */;
PrintReport(data, customSort);
}
}
Delegates are commonly used to decouple classes and interfaces from each other.
Here's a specific example. Suppose you had a UI class that was responsible for drawing a calendar, but you didn't want it to know exactly how to format the DateTime values into string.
You could define the class something like this:
public sealed class MyCalendarDrawer
{
private readonly Func<DateTime, string> _dateFormatter;
public MyCalendarDrawer(Func<DateTime, string> dateFormatter)
{
_dateFormatter = dateFormatter;
}
public void Draw()
{
// Do some work that involves displaying dates...
DateTime date = DateTime.Now;
string dateString = _dateFormatter(date);
// Display dateString somehow.
}
}
That way, MyCalendarDrawer doesn't need to know how to format the dates - it is told how to do it by being passed a delegate Func<DateTime, string> that it can call to do so.
Treating functions as first class types has its advantages. It gives you functional programming possibilities.
Take the classic case of "Event Handling" for example, you will certainly send a function pointer to another function as a call-back on occurance of an event.
Similarly, here is another hypothetical example
private void CallMeBack(out int type, Func<int> action)
{
type = action();
}
Now I can supply any function to this, like CallMeBack(a, ()=>return 1); and CallMeBack(a, ()=>return 2);
You should read about Delegates.
As example, delegates are useful to define a dynamic callback on a given method completion.
Pseudo-code example:
doSomething(); //your code
updateInterface(continueDoingSomething); //a generic method, passing a delegate
...
doAnythingElse();
updateInterface(continueDoingAnythingElse);
In this example, you could define a generic method "updateInterface" which, as a callback, calls a dynamic method passed in as a delegate.
If not using delegates, you would have to implement two (or more) different methods:
void updateInterfaceAndContinueDoingSomething(){}
void updateInterfaceAndContinueDoingAnythingElse(){}
Truth is, every single example where functions are passed to other functions can be expressed in term of objects implementing a given interface passed to functions.
In other words, there are no obvious reasons delegates are better than interfaces. Upcoming lambdas in Java are an example than you don't really need to be able to pass a function to another function to be able to have a concise syntax.
In yet another words, the ability to pass a function to another function is just a tool in your programmer's toolkit just as passing objectd to functions is. And while this is arguable which is better, one can have a language that doesn't support passing functions to functions at all - Java - and still be able to have the same expressiveness.