Assignment Examples: The One about Duck Typing in C#

Induction is a process of logical reasoning, based on the transition from private to general provisions. The famous “duck test” is a prime example of such a process: If it walks like a duck and quacks like a duck, it must be a duck.

Applied to programming languages, and in particular to object-oriented languages, the “duck test” takes on a special meaning. In dynamically typed languages, the semantics of the use of the object is determined by the current set of its methods and properties. For example, in a statically typed language which doesn’t support duck typing, it is possible to create the function with an object of the class “Duck” as a parameter with the call of “Quack” and “Walk” for methods of that object. In the duck typed language, the similar function can take some abstract object as a parameter and try to call the same methods. Something like duck typing is present in C#.

Foreach

Most books say that the interface System.Collections.IEnumerable should be implemented in the class to support the semantics of foreach. This is actually not true. If we talk about C #, it is not necessary to implement the mentioned interface.

If you open the C # Language Specification and look in section 8.8.4, you will see the following:

The type of the expression of a foreach statement must be a collection type (as defined below), and an explicit conversion (§6.2) must exist from the element type of the collection to the type of the iteration variable. If the expression has the value null, a System.NullReferenceException is thrown.

Type C is said to be a collection type if it implements the System.Collections.IEnumerable interface or implements the collection pattern by meeting all of the following criteria:

C contains a public instance method with the signature GetEnumerator() that returns a struct-type, class-type, or interface-type, which is called E in the following text:

E contains a public instance method with the signature MoveNext() and the return type bool.

E contains a public instance property named Current that permits reading the current value. The type of this property is said to be the element type of the collection type (msdn.microsoft.com).

So, the following code will compile and output the right message:

using System;
using System.Collections.Generic;

namespace DuckTyping
{
	class Collection
	{
		public Counter GetCounter()
		{
			return new Counter();
		}
	}

	class Counter
	{
		private bool next = true;

		public object curr
		{
			get{ return "Counter.curr"; }
		}

			public bool Next()
		{
			if (!next)
				return false;

			next = false;
			return true;
		}
	}

	class Program
	{
		static void Main()
		{
			foreach(object a in new Collection())
				Console.WriteLine(a);
		}
	}
}

Collection Initializers

This is a pretty pleasant innovation in C# 3.0:

var digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Now, we should determine the termine “Collection”. At this point, we can face some trouble. Before .NET 2.0, the interface System.Collections.Icollection was mostly useless. In 2.0, it was fixed. System.Collections.Generic.ICollection<T> allows you to add or delete elements, iterate through them using foreach, and get the amount of elements in the collection.

The argument list may thus be heterogeneous. In other words, with such a class:

public class Plurals : IDictionary<string,string> 
{
  public void Add(string singular, string plural);
  public void Add(string singular); 
  public void Add(KeyValuePair<string,string> pair); 
}

This initializer will be legal:

var myPlurals = new Plurals{ “collection”, { “name”, “ names” }, new KeyValuePair(“wolf”, “wolves”) };

Overload resolution is performed separately for each element of the initialization list so all three methods will be used.
Thanks for your attention!

References

8.8.4 The foreach statement. (2011, February 23). Retrieved July 12, 2016, from https://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx

Programming Assignments Help

We hope you like our sample. Need help with other C# programming code examples? Are you looking for a site where you can get homework help? AssignmentShark.com has a team of dedicated academic experts who are knowledgeable in different disciplines.

Remember that you can forget about your homework problem if you simply place an order on our site. Our experts are ready to assist you with any subject. If you are looking for someone to provide online assignment help for you, then you have found the right place. We are available 24/7 for your convenience – you can contact us any time you want. Just go to our order form, fill in your requirements, ask to do my programming task and set the deadline.

Leave a Reply

Your email address will not be published. Required fields are marked *

Customer testimonials

Submit your instructions to the experts without charge.