How to implement code like SomeObject.SomeFunction().SomeOtherFunction(); - c#

Today, I searched a line of code which was written like:
SomeObject.SomeFunction().SomeOtherFunction();
I am unable to understand this. I tried to search it on Google about this but no luck.
Please help me to understand this.

SomeObject has a function called SomeFunction(). This function returns an object (of an unknown type for us, based on your example). This object has a function called SomeOtherFunction().
The question "how to implement" is a bit vague to answer, though.

Consider the following
public class FirstClass
{
public SecondClass SomeFunction()
{
return new SecondClass();
}
}
public class SecondClass
{
public void SomeOtherFunction()
{
}
}
So the following are equivalent.
FirstClass SomeObject = new FirstClass();
SomeObject.SomeFuntion().SomeOtherFunction();
OR
FirstClass SomeObject = new FirstClass();
SecondClass two = SomeObject.SomeFuntion();
two.SomeOtherFunction();

This is called Fluent coding or method chaining and is a method of programming that allows you to chain commands together. It is very common in LINQ where you might have something like this:
var result = myList.Where(x => x.ID > 5).GroupBy(x => x.Name).Sort().ToList();
This would give you all the records greater than 5, then grouped by name, sorted and returned as a list. The same code could be written in long hand like this:
var result = myList.Where(x => x.ID > 5);
result = result.GroupBy(x => x.Name);
result = result.Sort();
result = result.ToList();
But you can see this is much more long winded.

This style of programming called FluentInterface style.
Eg:
internal class FluentStyle
{
public FluentStyle ConnectToDb()
{
// some logic
return this;
}
public FluentStyle FetchData()
{
// some logic
return this;
}
public FluentStyle BindData()
{
// some logic
return this;
}
public FluentStyle RefreshData()
{
// some logic
return this;
}
}
And the object can be created and method can be consumed as below;
var fluentStyle = new FluentStyle();
fluentStyle.ConnectToDb().FetchData().BindData().RefreshData();

This type of chaining may involve extension methods. These allow addition of new methods to existing classes (even those that you don't have the source code for).
e.g.
public static class StringExtender
{
public static string MyMethod1(this string Input)
{
return ...
}
public static string MyMethod2(this string Input)
{
return ...
}
}
....
public string AString = "some string";
public string NewString = AString.MyMethod1().MyMethod2();

This can be done using extension methods
public class FirstClass
{
}
public class SecondClass
{
}
public class ThridClass
{
}
public static class Extensions
{
public static SecondClass GetSecondClass(this FirstClass f)
{
return new SecondClass();
}
public static ThridClass GetThridClass(this SecondClass s)
{
return new ThridClass();
}
}
}
AND then you can ues
FirstClass f= new FirstClass();
f.GetSecondClass().GetThridClass();

Related

Common functions and helpers ASP.NET MVC

I don't get something, and if somebody can clarify:
I need to access this function / helper from here and there:
namespace Laf.Helpers
{
public class Common
{
public string TimeSpanToString(TimeSpan val)
{
return val.ToString(#"hh\:mm");
}
}
}
And in my controller I access it by:
var tmp = new Common();
string str = tmp.TimeSpanToString(tp.DepartureTime);
transferPoint.Add(
new ListTransferPointVM { PortName = tp.PortName, DepartureTime = str }
str);
And the question is how can I achieve and not have duplicate in every controller:
DepartureTime = TimeSpanToString(tp.DepartureTime)
Possible Answer
I just found a way that compiler is not frowning on:
public class TransferController : Controller
{
private Common common = new Common();
public ActionResult Index ()
{
...
and later, when I need it:
string time = common.TimeSpanToString((TimeSpan)variable);
You could make your method string TimeSpanToString(TimeSpan) a static method. This way you can access it without having to make a Common object. Your code will look as follows:
namespace Laf.Helpers
{
public class Common
{
public static string TimeSpanToString(TimeSpan val)
{
return val.ToString(#"hh\:mm");
}
}
}
And your Controller:
transferPoint.Add(
new ListTransferPointVM {
PortName = tp.PortName,
DepartureTime = Common.TimeSpanToString(tp.DepartureTime) }
Common.TimeSpanToString(tp.DepartureTime));
EDIT: As suggested by Michael Petrotta an extension method would be better. An implementation could be:
namespace LaF.ExtensionMethods
{
public static class MyExtensions
{
public static string TimeSpanToString(this TimeSpan ts)
{
return ts.ToString(#"hh\:mm");
}
}
}
You can now call the method like:
tp.DepartureTime.TimeSpanToString();
More on Extension Methods in C#

C# cast generic T in abstract class<T> to dynamic

This is what I want to do in C# (within class Helper - without generic arguments),
List<AbstractClass<dynamic>> data;
public void Add<T>(AbstractClass<T> thing)
{
this.data.Add((AbstractClass<dynamic>) thing);
}
This helper class would take and work with AbstractClass<> objects and give back AbstractClass<> of specific generic type. AbstractClass<T> contains many functions which return T / take in T like public T Invoke().
For Helper class T cannot be known beforehand. The Add<T>(.. thing) function is not in a class of type T.
To be used like this in Helper class's functions,
foreach(var c in data.Where(x => ...))
{
// public T Invoke() { ... } function within AbstractClass<T>
var b = c.Invoke();
// logic
}
This also fails,
List<AbstractClass<object>> data;
public void Add<T>(AbstractClass<T> thing)
{
this.data.Add((AbstractClass<object>) thing);
}
Now I think I can have,
List<dynamic> data; // or List<object> data;
public void Add<T>(AbstractClass<T> thing)
{
this.data.Add(thing);
}
but I want the constraint that List named data has only elements of type like
ConcreteClass : AbstractClass<OtherClass>
So we would know that there is an public T Invoke() function but we do not know what it returns. This is helpful to avoid mistakes of say misspelling Invocke and only knowing at run-time.
I want to avoid casting to dynamic every time to invoke functions that give back generic type T
To do what you want to do you are going to need to use a Contravariant interface
public class Program
{
static void Main()
{
var m = new Helper();
m.Add(new ConcreteClass());
m.Process();
}
class Helper
{
List<IAbstractClass<OtherClassBase>> data = new List<IAbstractClass<OtherClassBase>>();
public void Add(IAbstractClass<OtherClassBase> thing)
{
this.data.Add(thing);
}
public void Process()
{
foreach(var c in data.Where(x => x.ShouldBeProcessed()))
{
var b = c.Invoke();
Console.WriteLine(b.Question);
var castData = b as OtherClass;
if (castData != null)
Console.WriteLine(castData.Answer);
}
}
}
public interface IAbstractClass<out T>
{
bool ShouldBeProcessed();
T Invoke();
}
abstract class AbstractClass<T> : IAbstractClass<T>
{
public bool ShouldBeProcessed()
{
return true;
}
public abstract T Invoke();
}
class ConcreteClass : AbstractClass<OtherClass>
{
public override OtherClass Invoke()
{
return new OtherClass();
}
}
class OtherClassBase
{
public string Question { get { return "What is the answer to life, universe, and everything?"; } }
}
class OtherClass : OtherClassBase
{
public int Answer { get { return 42; } }
}
}
You do not need to tell Add what kind of class you are passing it, all that matters is it derives from the type specified. You could do public void Add(IAbstractClass<object> thing) and every class would work, but Invoke() would only return objects inside the foreach loop.
You need to figure out what is the most derived class you want Invoke() to return and that is what you set as the type in the list.
Maybe this will work for you:
public class Program
{
static void Main()
{
var m1 = new Helper<OtherClass>();
m1.Add(new ConcreteClass());
var m2 = new Helper<int>();
m2.Add(new ConcreteClass2());
}
class Helper<T>
{
List<AbstractClass<T>> data = new List<AbstractClass<T>>();
public void Add<T1>(T1 thing) where T1 : AbstractClass<T>
{
this.data.Add(thing);
}
}
class AbstractClass<T> { }
class OtherClass { }
class ConcreteClass : AbstractClass<OtherClass> { }
class ConcreteClass2 : AbstractClass<int> { }
}

MOQ: Setting up a method which fills a collection inside the object passed as parameter

I have a class named "CollectionPager" which has a collection inside that of type List. I have a method "RetrieveList" which takes a "CollectionPager" as input and populates "List" in side that. This method doesn't return any value.
I need to mock a function which calls "RetrieveList". However, since it doesn't return any value, whatever input was fed into Mock is not taken into consideration and this collection(List) always has a count of 0.
Any possible ways to resolve this?
I guess you need the Callback (see also Moq quickstart) method to setup some logic when mocking a void function.
Here is sample test which demonstrates the usage:
var mock = new Mock<IRetrieveListService>();
mock.Setup(m => m.RetrieveList(It.IsAny<CollectionPager>()))
.Callback<CollectionPager>(p =>
{
p.List.Add("testItem1");
p.List.Add("testItem2");
});
var sut = new OtherService(mock.Object);
sut.SomeMethodToTest();
Assuming your classes looks like something like these:
public class CollectionPager
{
public CollectionPager()
{
List = new List<string>();
}
public List<string> List { get; private set; }
}
public interface IRetrieveListService
{
void RetrieveList(CollectionPager pager);
}
public class RetrieveListService : IRetrieveListService
{
public void RetrieveList(CollectionPager pager)
{
pager.List.Add("item1");
pager.List.Add("item2");
}
}
public class OtherService
{
private readonly IRetrieveListService retrieveListService;
public OtherService(IRetrieveListService retrieveListService)
{
this.retrieveListService = retrieveListService;
}
public void SomeMethodToTest()
{
var collectionPager = new CollectionPager();
retrieveListService.RetrieveList(collectionPager);
// in your test collectionPager.Item contains: testItem1, testItem2
}
}

how to implement Collection object

how to implement collection objects of my class?
something like MatchCollection or CookieCollection
For example:
I have the following class:
public class theParserClass
{
public theParserClass(string baa)
{
//..
}
public string pro1
{
get { /* etc */ }
}
}
and the collection that I want to implement:
public class theParserClassResultCollection
{
private ParserResultCollection result;
public theParserClassResultCollection(string[] baa)
{
foreach(string foo in baa)
{
var data = new theParserClass(foo);
result.Add(data);
}
}
public ParserResultCollection()
{
return result;
}
}
I hope this is clear. Thanks in advance
you can use the ObservableCollection like this:
public ObservableCollection<ParserClass> GetCollection(string[] baa)
{
var result = new ObservableCollection<ParserClass>();
foreach(string foo in baa)
{
var data = new ParserClass(foo);
result.Add(data);
}
return result;
}
public class ParserClass
{
public ParserClass (string baa)
{
//..
}
public string pro1
{
get { /* etc */ }
}
}
msdn : http://msdn.microsoft.com/en-us/library/ms668604.aspx
hope this helps
First off, you are declaring what appears to be the constructor of ParserResultCollection inside the class theParserResultCollection. Don't really know what that is supposed to mean.
The general idea you can use is to make a wrapper class over an existing collection (inheritance by composition) and provide the methods that you need using the inner collection object. Like:
public class ParserResultCollection
{
private List<ParserClass> collection;
public ParserResultCollection(string[] param)
{
collection = new List<ParserClass>(param);
}
public void Add(ParserClass item)
{
collection.Add(item);
}
// whatever else you need.
}
Of course, if you don't need any other special functionality with respect to the existing collections, just use them instead.
And drop the "the", just ParserResultCollection. It's cleaner.
You could try this:
public class Collection<T> : IList<T>,
ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
http://msdn.microsoft.com/en-us/library/ms132397.aspx

How to change the class of an object dynamically in C#?

Suppose I have a base class named Visitor, and it has 2 subclass Subscriber and NonSubscriber.
At first a visitor is start off from a NonSubscriber, i.e.
NonSubscriber mary = new NonSubscriber();
Then later on this "mary" subscribed to some services, and I want to change the type of "mary" to Subscriber.
What is the conventional way to do that?
can't do that. sorry. C# is not a dynamic language.
You will have to create a new mary = new Subscriber(); and copy all relevant properties.
But a better approach might be to model it differently: Give Visitor a list of subscriptions. An empty list means a NonSubscriber.
You cant do this type of conversion.
What you should do is treat mary as a visitor, and when time arrives, create a new instance of "subscriber":
Visitor mary = new NonSubscriber();
// Do some Visitor operations
...
// Now mary is a Subscriber
mary = new Subscriber();
You could use the GOF design patterns State or Strategy to model such an behaviour. Using these patterns, it seems during runtime as if the class of the objects has been changed.
It seems that you have some design problems. I think that it would be better to redesign your code like:
class Visitor
{
private bool isSubscriber = false;
public bool IsSubscriber
{
get { return isSubscriber; }
}
public void Subscribe()
{
// do some subscribing stuff
isSubscriber = true;
}
public void Unsubscribe()
{
// do some unsubscribing stuff
isSubscriber = false;
}
}
You cannot change the type of a variable at runtime. You need to create a new instance.
mary = new Subscriber();
Create a Subscriber constructor that takes a NonSubscriber object as a parameter, or create a method on the NonSubscriber object that returns a Subscriber to save you having to writer the mappping code in multiple places.
It seems like you are encoding information incorrectly into your class hierarchy. It would make more sense to use a different pattern than sub classing here. For example, use only one class (visitor, or perhaps you could name it potential subscriber, whatever seems appropriate) and encode information on the services the object is subscribed to, moving the dynamically changing behavior behind a "Strategy" pattern or some such. There's very little detail in your example, but one thing you could do in C# is to make a "subscriber" property which would change the behavior of the object when the state of the property was changed.
Here's a contrived somewhat related example:
class Price
{
private int priceInCents;
private bool displayCents;
private Func<string> displayFunction;
public Price(int dollars, int cents)
{
priceInCents = dollars*100 + cents;
DisplayCents = true;
}
public bool DisplayCents
{
get { return displayCents; }
set
{
displayCents = value;
if (displayCents)
{
this.displayFunction = () => String.Format("{0}.{1}", priceInCents / 100, priceInCents % 100);
}
else
{
this.displayFunction = () => (priceInCents / 100).ToString();
}
}
}
public string ToString()
{
return this.displayFunction();
}
}
public class User
{
public Subscription Subscription { get; set; }
public void HandleSubscription()
{
Subscription.Method();
}
}
public abstract class SubscriptionType
{
public abstract void Method();
}
public class NoSubscription : SubscriptionType
{
public override void Method()
{
// Do stuff for non subscribers
}
}
public class ServiceSubscription : SubscriptionType
{
public override void Method()
{
// Do stuff for service subscribers
}
}
public class Service2Subscription : SubscriptionType
{
public override void Method()
{
// Do stuff for service2 subscribers
}
}
Think the code explains my answer :)
Adding to the other answers and your comment, you indeed can use the state pattern for your purpose, it would go something like this:
public class MyProgram
{
public void Run()
{
Visitor v = new Visitor("Mary");
Debug.Assert(v.SubscriptionLinkText == "Join now");
v.IsSubscribed = true;
Debug.Assert(v.SubscriptionLinkText == "Today's special");
v.IsSubscribed = false;
Debug.Assert(v.SubscriptionLinkText == "Join now");
}
}
public class Visitor
{
public string Name { get; set; }
private bool _isSubscribed;
public bool IsSubscribed
{
get { return this._isSubscribed; }
set
{
if (value != this._isSubscribed)
{
this._isSubscribed = value;
this.OnSubscriptionChanged();
}
}
}
private SubscriptionBase _subscription;
public string SubscriptionLinkText
{
get { return this._subscription.LinkText; }
}
public Visitor(string name)
{
this.Name = name;
this._isSubscribed = false;
this.OnSubscriptionChanged();
}
private void OnSubscriptionChanged()
{
// Consider also defining an event and raising it here
this._subscription =
SubscriptionBase.GetSubscription(this.IsSubscribed);
}
}
abstract public class SubscriptionBase
{
// Factory method to get instance
static public SubscriptionBase GetSubscription(bool isSubscribed)
{
return isSubscribed ?
new Subscription() as SubscriptionBase
: new NoSubscription() as SubscriptionBase;
}
abstract public string LinkText { get; }
}
public class Subscription : SubscriptionBase
{
public override string LinkText
{
get { return "Today's Special"; }
}
}
public class NoSubscription : SubscriptionBase
{
public override string LinkText
{
get { return "Join now"; }
}
}

Categories

Resources