C# -Interview Question Anonymous Type - c#-3.0

Recently i was asked to prove the power of C# 3.0 in a single line( might be tricky)
i wrote
new int[] { 1, 2, 3 }.Union(new int[]{10,23,45}).
ToList().ForEach(x => Console.WriteLine(x));
and explained you can have (i) anonymous array (ii) extension method (iii)lambda and closure all in a single line.I got spot offer.
But.....
The interviewer asked me how will you convert an anonymous type into known type :(
I explained
public class Product
{
public double ItemPrice { private set; get; }
public string ItemName { private set; get; }
}
var anony=new {ItemName="xxxx",ItemPrice=123.56};
you can't assign product a=anony;
The interviewer replied there is 200% chance to do that
if you have a small work around.I was clueless.
As usual,I am waiting for your valuable reply(Is it possible?).

You're right, you can't make this assignment:
product a=anony;
MSDN: Anonymous Types (C# Programming Guide)
An anonymous type cannot be cast to
any interface or type except for
object.

Maybe something like this:
class Program
{
static T Cast<T>(object target, T example)
{
return (T)target;
}
static object GetAnon()
{
return new { Id = 5 };
}
static void Main()
{
object anon = GetAnon();
var p = Cast(anon, new { Id = 0 });
Console.WriteLine(p.Id);
}
}
Remark: never write or rely on such a code.

May be try the examples shown here..they try to do something similar..
http://www.codeproject.com/KB/linq/AnonymousTypeTransform.aspx
http://www.inflecto.co.uk/Inflecto-Blog/post/2009/11/12/IQueryable-Sorting-Paging-Searching-and-Counting.aspx

var list = anony.Select(x=> new Product {
ItemPrice = x.ItemPrice, ItemName = x.ItemName }).ToList();

Related

Can I make my own getters and setters and should I?

Should I make my own getters and setters in Swift? Im confused by the built in getters ad setters...is this even needed?
//properties for the resident
private var name: String!
var apartmentNumber: String!
var email : String!
var phoneNumber : String!
public func getName()->String{
return self.name
}
public func setName(name : String){
self.name = name
}
}
I've written an article for exactly this. I'll paste it here.
Stop writing getters and setters in Swift
I see this time and time again, and it's about time I write an article in one place to consolidate all my thoughts. If you find yourself writing code that looks like this, listen up:
public class C {
private var _i: Int = 0
public var i: Int {
get {
return self._i
}
set {
self._i = newValue
}
}
}
This pattern* is completely pointless in Swift, and I'll explain why, but firstly we need to take a short detour through Java land. Why Java? Because most of the people I run into who write Swift like this have some sort of Java background, either
because it was taught in their computer sceince courses, or
because they're coming over to iOS development, from Android
What's the point of getters and setters?
Suppose we have the following class in Java:
public class WeatherReport {
public String cityName;
public double temperatureF;
public WeatherReport(String cityName, double temperatureF) {
this.cityName = cityName;
this.temperatureF = temperatureF;
}
}
If you showed this class to any CS prof, they're surely going to bark at you for breaking encapsulation. But what does that really mean? Well, imagine how a class like this would be used. Someone would write some code that looks something like this:
WeatherReport weatherReport = weatherAPI.fetchWeatherReport();
weatherDisplayUI.updateTemperatureF(weatherReport.temperatureF);
Now suppose you wanted to upgrade your class to store data in a more sensible temperature unit (beating the imperial system dead horse, am I funny yet?) like Celcius or Kelvin. What happens when you update your class to look like this:
public class WeatherReport {
public String cityName;
public double temperatureC;
public WeatherReport(String cityName, double temperatureC) {
this.cityName = cityName;
this.temperatureC = temperatureC;
}
}
You've changed the implementation details of your WeatherReport class, but you've also made an API breaking change. Because temperatureF was public, it was part of this class' API. Now that you've removed it, you're going to cause compilation errors in every consumer that depended on the exitense of the temperatureF instance variable.
Even worse, you've changed the semantics of the second double argument of your constructor, which won't cause compilation errors, but behavioural errors at runtime (as people's old Farenheit based values are attemped to be used as if they were celcius values). However, that's not an issue I'll be discussing in this article.
The issue here is that consumers of this class will be strongly coupled to the implementation details of your class. To fix this, you introduce a layer of seperation between your implementation details and your interface. Suppose the Farenheit version of our class was implemented like so:
public class WeatherReport {
private String cityName;
private double temperatureF;
public WeatherReport(String cityName, double temperatureF) {
this.cityName = cityName;
this.temperatureF = temperatureF;
}
public String getCityName() {
return this.cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public double getTemperatureF() {
return this.temperatureF;
}
public void setTemperatureF(double temperatureF) {
this.temperatureF = temperatureF;
}
}
The getters and setters are really basic methods that access or update our instance variables. Notice how this time, our instance variables are private, and only our getters and setters are public. A consumer would use this code, as so:
WeatherReport weatherReport = weatherAPI.fetchWeatherReport();
weatherDisplayUI.updateTemperatureF(weatherReport.getTemperatureF());
This time, when we make the upgrade to celcius, we have the freedom to change our instance variables, and tweak our class to keep it backwards compatible:
public class WeatherReport {
private String cityName;
private double temperatureC;
public WeatherReport(String cityName, double getTemperatureC) {
this.cityName = cityName;
this.temperatureC = temperatureC;
}
public String getCityName() {
return this.cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
// Updated getTemperatureF is no longer a simple getter, but instead a function that derives
// its Farenheit value from the Celcius value that actuallyed stored in an instance variable.
public double getTemperatureF() {
return this.getTemperatureC() * 9.0/5.0 + 32.0;
}
// Updated getTemperatureF is no longer a simple setter, but instead a function
// that updates the celcius value stored in the instance variable by first converting from Farenheit
public void setTemperatureF(double temperatureF) {
this.setTemperatureC((temperatureF - 32.0) * 5.0/9.0);
}
// Mew getter, for the new temperatureC instance variable
public double getTemperatureC() {
return this.temperatureC;
}
// New setter, for the new temperatureC instance variable
public void setTemperatureC(double temperatureC) {
this.temperatureC = temperatureC;
}
}
We've added new getters and setters so that new consumers can deal with temperatures in Celcius. But importantly, we've re-implemented the methods that used to be getters and setters for temperatureF (which no longer exists), to do the appropraite conversions and forward on to the Celcius getters and setters. Because these methods still exist, and behave identically as before, we've successfully made out implementation change (storing F to storing C), without breaking our API. Consumers of this API won't notice a difference.
So why doesn't this translate into Swift?
It does. But simply put, it's already done for you. You see, stored properties in Swift are not instance variables. In fact, Swift does not provide a way for you to create or directly access instance variables.
To understand this, we need to have a fuller understanding of what properties are. There are two types, stored and computed, and neither of them are "instance variables".
Stored properties: Are a combination of a comiler-synthesized instance variable (which you never get to see, hear, touch, taste, or smell), and the getter and setter that you use to interact with them.
Computed proepties: Are just a getter and setter, without any instance variable to act as backing storage. Really, they just behave as functions with type () -> T, and (T) -> Void, but have a pleasant dot notation syntax:
print(weatherReport.temperatureC)
weatherReport.temperatureC = 100
rather than a function calling synax:
print(weatherReport.getTemperatureC())
weatherReport.setTemperatureC(100)
So in fact, when you write:
class C {
var i: Int
}
i is the name of the getter and setter for an instance variable the compiler created for you. Let's call the instance variable $i (which is not an otherwise legal Swift identifier). There is no way to directly access $i. You can only get its value by calling the getter i, or update its value by calling its setter i.
So lets see how the WeatherReport migration problem looks like in Swift. Our initial type would look like this:
public struct WeatherReport {
public let cityName: String
public let temperatureF: Double
}
Consumers would access the temperature with weatherReport.temperatureF. Now, this looks like a direct access of an isntance variable, but remember, that's simply not possible in Swift. Instead, this code calls the compiler-syntehsized getter temperatureF, which is what accesses the instance variable $temperatureF.
Now let's do our upgrade to Celcius. We will first update our stored property:
public struct WeatherReport {
public let cityName: String
public let temperatureC: Double
}
This has broken our API. New consumers can use temperatureC, but old consumers who depended on temperatureF will no longer work. To support them, we simply add in a new computed property, that does the conversions between Celcius and Fahenheit:
public struct WeatherReport {
public let cityName: String
public let temperatureC: Double
public var temperatureF: Double {
get { return temperatureC * 9/5 + 32 }
set { temperatureC = (newValue - 32) * 5/9 }
}
}
Because our WeatherReport type still has a getter called temperatureF, consumers will behave just as before. They can't tell whether a property that they access is a getter for a stored property, or a computed property that derives its value in some other way.
So lets look at the original "bad" code. What's so bad about it?
public class C {
private var _i: Int = 0
public var i: Int {
get {
return self._i
}
set {
self._i = newValue
}
}
}
When you call c.i, the following happens:
You access the getter i.
The getter i accesses self._i, which is yet another getter
The getter _i access the "hidden" instance variable $i
And it's similar for the setter. You have two layers of "getterness". See what that would look like in Java:
public class C {
private int i;
public C(int i) {
this.i = i;
}
public int getI1() {
return this.i;
}
public void setI1(int i) {
this.i = i;
}
public int getI2() {
return this.getI1();
}
public void setI2(int i) {
this.setI1(i);
}
}
It's silly!
But what if I want a private setter?
Rather than writing this:
public class C {
private var _i: Int = 0
public var i: Int {
get {
return self._i
}
}
}
You can use this nifty syntax, to specify a seperate access level for the setter:
public class C {
public private(set) var i: Int = 0
}
Now isn't that clean?
There is no need to create setters and getters for stored properties in Swift and you shouldn't create them either.
You can control the accessibility of getters/setters separately when you declare a property.
public private(set) var name: String // public getter, private setter
If you want to implement some custom logic in your setter, you should use property observer, i.e. didSet/willSet.
var name: String {
didSet {
// This is called every time `name` is set, so you can do your custom logic here
}
}
You will hardly come across the need to create your own getters and setters.
Swift's computed property lets you use getters and setters in a very simple way.
Eg: below defined is a computed property circleArea that returns area of circle depending on radius.
var radius: Float = 10
var circleArea: Float {
get {
return .pi * powf(radius, 2)
}
set {
radius = sqrtf(newValue / .pi)
}
}
While you can observe a stored value and perform some task using property observers:
var radius: Float = 10 {
willSet {
print("before setting the value: \(value)")
}
didSet {
print("after the value is set: \(value)")
}
}
radius += 1
// before setting the value: 10.0
// after the value is set: 11.0
However if you feel like using getter setter, you can define appropriate functions for that. Below defined is an extension on Integer to get and set properties value.
extension Int {
func getValue() -> Int {
return self
}
mutating func setValue(_ val: Int) {
self = val
}
}
var aInt: Int = 29
aInt.getValue()
aInt.setValue(45)
print(aInt)
// aInt = 45

Find direct & indirect method usages if method is overriden in base class

please, help me to figure out how to write the query :)
The code is:
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
var man = new Man("Joe");
Console.WriteLine(man.ToString());
}
}
public class SuperMan
{
public SuperMan(string name)
{
this.name = name;
}
public override string ToString()
{
return name;
}
string name;
}
public class Man : SuperMan
{
public Man(string name) : base(name)
{
}
}
}
I want to find all direct and indirect dependencies (methods) to Man.ToString(). There is only one call in Main() method.
The query I'm trying is:
from m in Methods
let depth0 = m.DepthOfIsUsing("ConsoleApplication1.SuperMan.ToString()")
where depth0 >= 0 orderby depth0
select new { m, depth0 }.
but it doesn't find dependent Program.Main() method....
How to modify query so that it finds usages for such kind of methods?
First let's look at direct callers. We want to list all methods that calls SuperMan.ToString() or any ToString() methods overriden by SuperMan.ToString(). It can looks like:
let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
from m in Application.Methods.UsingAny(baseMethods)
where m.IsUsing("ConsoleApplication1.Man") // This filter can be added
select new { m, m.NbLinesOfCode }
Notice we put a filter clause, because in the real world pretty much every method calls object.ToString() (this is a particular case).
Now to handle indirect calls this is more tricky. We need to call the magic FillIterative() extension methods on generic sequences.
let baseMethods = Application.Methods.WithFullName("ConsoleApplication1.SuperMan.ToString()").Single().OverriddensBase
let recursiveCallers = baseMethods.FillIterative(methods => methods.SelectMany(m => m.MethodsCallingMe))
from pair in recursiveCallers
let method = pair.CodeElement
let depth = pair.Value
where method.IsUsing("ConsoleApplication1.Man") // Still same filter
select new { method , depth }
Et voilĂ !

How to design the classes with OOP?

I have problems about classes design now. The question is as follows:
I want to design classes for fruit and juicer. The classes for fruit (Apple, pear peach) are done. Now I want to design classes for juicer.
The requirement for juicer are:
1.Juicers take specific fruit (apple, pear, peach) and produce juice. NOTE: there may be mixed juice (such as flavor of apple and pear).
2.One kind of juicer can only produce one kind of juice.
3.Juicers have space to store fruit, and we can know how many apples or pears are still there. (We assume that every time one juicer uses one apple or pear).
Could anyone give me some advices?
If your language supports generics (as do C# and Java), the simplest solution would be to make the Juicer generic:
public class Juicer<T>
{
private T[] fruits;
public Juicer(T[] fruits)
{
this.fruits = fruits;
}
public FruitCount
{
get { return this.fruits.Length; }
}
// Other members can go here...
}
You can create one object that's a Juicer<Apple>, another as a Juicer<Pear>, and so on. A Juicer<Apple> can only contain Apple objects, etc.
Mark's answer is pretty good and a good start... I'd expand a bit. I probably wouldn't use an array for fruits since you will be adding, removing etc... probably easier to implement with a list or similar. Also, Laine says he wants multiple fruits in some juicers.. that complicates things a bit and gives us some decisions to make.
If it will always be a maximum of two fruits, I would probably just make two juicer classes similar to those in Mark's answer:
public interface IFruit
{
string Name {get;}
}
public class Apple : IFruit
{
public string Name { get {return "Apple";} }
}
public class Pear : IFruit
{
public string Name { get {return "Pear";} }
}
public class Juicer<IFruit>
{
private IList<IFruit> fruits;
public Juicer(IList<IFruit> fruits)
{
this.fruits = fruits;
}
public int FruitCount
{
get { return this.fruits.Count; }
}
// Other members can go here...
}
public class TwoFruitJuicer<IFruit, IFruit2>
{
private IList<IFruit> fruits;
private IList<IFruit2> fruits2;
public TwoFruitJuicer(IList<IFruit> fruits, IList<IFruit2> fruits2)
{
this.fruits = fruits;
this.fruits2 = fruits2;
}
public int FruitCount
{
get { return this.fruits.Count + this.fruits2.Count; }
}
// Other members can go here...
}
But, say you wanted 3 or 4 different juicers combined...
public class MulitJuicer
{
private IList<Juicer<IFruit>> _juicers;
public MulitJuicer(IList<Juicer<IFruit>> juicers)
{
this._juicers = juicers;
}
public int FruitCount
{
get {
int allFruitCount = 0;
foreach (var j in _juicers)
{
allFruitCount += j.FruitCount;
}
return allFruitCount;
}
}
}
However, That would probably be pretty difficult to use, a lot of lists inside of lists to keep track of build up and whatnot... what if you wanted just once juicer that you could just dump a bunch of fruits in? We can use Reflection to verify that only allowed fruits are put in the juicer:
public class MultiFruitJuicer
{
private IList<Type> _juiceTypes;
private IList<IFruit> _fruits;
public MultiFruitJuicer(IList<Type> juiceTypes, IList<IFruit> fruits)
{
_juiceTypes = juiceTypes;
_fruits = fruits;
if (!ValidateFruits())
{
//you may not want to actually throw here...
throw new Exception("Not all proper fruit types");
}
}
public bool ValidateFruits()
{
//there are about a million ways to do this... this is probably not the best...
foreach(var f in _fruits)
{
if (!_juiceTypes.Contains(f.GetType()))
{
return false;
}
}
return true;
}
public int FruitCount
{
get { return this._fruits.Count; }
}
}
I would start by implementing Builder design pattern for the
design classes for juicer
It'll help you to construct a complex object (juice) and separate its representation, so that the same construction process can create different representations (kinds of juice).
Add some interface (IFruit) and base class (shared code for Weight, Size etc.) to
classes for fruit (Apple, pear peach)
Each Juicer will have
ICollection<IFruit> fruits
that can be managed - .Count(), .Add(IFruit) or .Remove(IFruit).

Creating an object passing a lambda expression to the constructor

I have an object with a number of properties.
I want to be able to assign some of these properties when I call the constructor.
The obvious solution is to either have a constructor that takes a parameter for each of the properties, but that's nasty when there are lots. Another solution would be to create overloads that each take a subset of property values, but I could end up with dozens of overloads.
So I thought, wouldn't it be nice if I could say..
MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);
The problem is, I'm too dim to work out how to do it.
Do you know?
C# 3 allows you to do this with its object initializer syntax.
Here is an example:
using System;
class Program
{
static void Main()
{
Foo foo = new Foo { Bar = "bar" };
}
}
class Foo
{
public String Bar { get; set; }
}
The way this works is that the compiler creates an instance of the class with compiler-generated name (like <>g__initLocal0). Then the compiler takes each property that you initialize and sets the value of the property.
Basically the compiler translates the Main method above to something like this:
static void Main()
{
// Create an instance of "Foo".
Foo <>g__initLocal0 = new Foo();
// Set the property.
<>g__initLocal0.Bar = "bar";
// Now create my "Foo" instance and set it
// equal to the compiler's instance which
// has the property set.
Foo foo = <>g__initLocal0;
}
The object initializer syntax is the easiest to use and requires no extra code for the constructor.
However, if you need to do something more complex, like call methods, you could have a constructor that takes an Action param to perform the population of the object.
public class MyClass
{
public MyClass(Action<MyClass> populator)
{
populator.Invoke(this);
}
public int MyInt { get; set; }
public void DoSomething()
{
Console.WriteLine(this.MyInt);
}
}
Now you can use it like so.
var x = new MyClass(mc => { mc.MyInt = 1; mc.DoSomething(); });
Basically what Andrew was trying to say is if you have a class (MyObject for eg) with N properties, using the Object Initializer syntax of C# 3.0, you can set any subset of the N properties as so:
MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};
You can set any of the properties / fields that way./
class MyObject
{
public MyObject(params Action<MyObject>[]inputs)
{
foreach(Action<MyObject> input in inputs)
{
input(this);
}
}
}
I may have the function generic style wrong, but I think this is sort of what you're describing.

Question about var type

I am new to C# 3.0 var type. Here I have a question about this type. Take the following simple codes in a library as example:
public class MyClass {
public var Fn(var inValue)
{
if ( inValue < 0 )
{
return 1.0;
}
else
{
return inValue;
}
}
}
I think the parameter is an anonymous type. If I pass in a float value, then the Fn should return a float type. If a double value type is passed in, will the Fn return a double type? How about an integer value type as input value?
Actually, I would like to use var type with this function/method to get different return types with various input types dynamically. I am not sure if this usage is correct or not?
You can't use var for return values or parameter types (or fields). You can only use it for local variables.
Eric Lippert has a blog post about why you can't use it for fields. I'm not sure if there's a similar one for return values and parameter types. Parameter types certainly doesn't make much sense - where could the compiler infer the type from? Just what methods you try to call on the parameters? (Actually that's pretty much what F# does, but C# is more conservative.)
Don't forget that var is strictly static typing - it's just a way of getting the compiler to infer the static type for you. It's still just a single type, exactly as if you'd typed the name into the code. (Except of course with anonymous types you can't do that, which is one motivation for the feature.)
EDIT: For more details on var, you can download chapter 8 of C# in Depth for free at Manning's site - this includes the section on var. Obviously I hope you'll then want to buy the book, but there's no pressure :)
EDIT: To address your actual aim, you can very nearly implement all of this with a generic method:
public class MyClass
{
public T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
// This is the tricky bit.
return 1.0;
}
else
{
return inValue;
}
}
}
As shown in the listing, the tricky bit is working out what "1" means for an arbitrary type. You could hard code a set of values, but it's a bit ugly:
public class MyClass
{
private static readonly Dictionary<Type, object> OneValues
= new Dictionary<Type, object>
{
{ typeof(int), 1 },
{ typeof(long), 1L },
{ typeof(double), 1.0d },
{ typeof(float), 1.0f },
{ typeof(decimal), 1m },
};
public static T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
object one;
if (!OneValues.TryGetValue(typeof(T), out one))
{
// Not sure of the best exception to use here
throw new ArgumentException
("Unable to find appropriate 'one' value");
}
return (T) one;
}
else
{
return inValue;
}
}
}
Icky - but it'll work. Then you can write:
double x = MyClass.Fn(3.5d);
float y = MyClass.Fn(3.5f);
int z = MyClass.Fn(2);
etc
You cannot use var as a return type for a method.