A look at IEnumerator and IEnumerable interfaces in C#

There are two interfaces which are at the base of many classes and the logic we use daily, to implement .Net based applications. These two interfaces are closely related to each other and provide a fuctionality that makes working with a Collection, fun. These are interfaces are IEnumerator and IEnumerable

Both of these interfaces work together. We need a class to implement IEnumerator interface, which provides implementations for Current property , MoveNext() and Reset() methods like below.

First, consider a class Job, around which all the logic will surround

    public class Job
    {
        public Job(string _jobName, int _duration)
        {
            this.jobName = _jobName;
            this.duration = _duration;
        }

        public string jobName;
        public int duration;
    }

Now, we have class that implements IEnumerator with an underlying array of Job objects:

    class JobsList : IEnumerator
    {
        Job[] jobs;
        int position = -1;

        public JobsList(Job[] _jobs)
        {
            jobs = _jobs;
        }

        #region IEnumerator Members

        public object Current
        {
            get
            {
                try
                {
                    return jobs[position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }

        public bool MoveNext()
        {
            position++;
            return (position < jobs.Length);
        }

        public void Reset()
        {
            position = -1;
        }

        #endregion
    }

Now consider another class Jobs. This class implements IEnumerable interface method GetEnumerator() returns IEnummerator object which holds indexed access to underlying array of Job objects as follows:

    class Jobs : IEnumerable
    {
        #region IEnumerable Members

        Job[] jobs;

        public Jobs(Job[] _jobsArray)
        {
            jobs = new Job[_jobsArray.Length];

            for (int i = 0; i < _jobsArray.Length; i++)
            {
                jobs[i] = _jobsArray[i];
            }
        }

        public IEnumerator GetEnumerator()
        {
            return new JobsList(jobs);
        }

        #endregion
    }

This is how now can use and manipulate our newly created IEnumerator object

        static void Main(string[] args)
        {
            // create new Job Array
            Job[] jobsArray = 
                 new Job[] { new Job("JobA", 1), new Job("JobB", 2), new Job("JobC", 3) };

            // // create new IEnumerable 
            Jobs jobs = new Jobs(jobsArray);

            // // create new IEnumerator
            IEnumerator jobsEnummerator = jobs.GetEnumerator();

            // following are some you can work over 
            // ways we can works over IEnumerator object
            while (jobsEnummerator.MoveNext())
            { }

            //  or using foreach
            foreach (Job job in jobs)
            { }
        }

Implicit versus Explicit implementation of Interfaces in C#

What is the differences in implementing an interfaces implicitly or explicitly in C#?

Suppose we have an interface IWriter as follows

    public interface IWriter
    {
        public void WrtiteTo()
        { }
    }

Implicit: When we implement an interface implicitly, the implementing class exposes new behaviours. It is simply adding the methods, properties or other items required by the interface directly to the class and as public methods. So winding up, A member does this work for you in class which is implementing certain interface. Here is the sample which implements IWriter Interface implicitly:

    public class DocumentWriter : IWriter
    {
        #region IWriter Members
        public void WrtiteTo()
        {
            // Some Logic here
        }
        #endregion
    }

Implicit: On the other hand Explicit implementation are exposed by the use of interface itself itself. Here is the sample which implements IWriter Interface Explicitly:

    public class DocumentWriter : IWriter
    {
        #region IWriter Members
        void IWriter.WrtiteTo()
        {
             // Some Logic here
        }
        #endregion
    }

How to check if printer is ready using c#

Say we have a document and we need to print it directly from our program instead of asking for help from PrintDialog or some other built-in feature. Before we send command to the printer, to print, we do need to check that printer is ready for command execution and there is no problem with it. Other wise, printer may raise error for any reason like, out of paper or ink problems or any thing else. This will cause an exception to be raised which is going to make the customer think .$5^&*…. about us which is not desirable.

So, is there any way to check if the device is ready ? before we send the print command ?

Here are two of the several methods, we can use to do so

METHOD 1:

        public bool CheckMyPrinter(string printerToCheck)
        {
          ManagementObjectSearcher searcher = new  
              ManagementObjectSearcher("SELECT * FROM   Win32_Printer"); 

          bool IsReady = false;
          foreach (ManagementObject printer in searcher.Get())
          {    
            if (printer["Name"].ToString().ToLower().Equals(printerToCheck))
            {     
              if (printer["WorkOffline"].ToString().ToLower().Equals("false"))
                {
                  IsReady = true;
                }                    
            }      
          }
          return IsReady ;
        }

METHOD 2: Will throw Exception, but you can catch it and work accordingly

            bool printerStatus = false;
            try
            {
                PrintDocument pd = new PrintDocument                                            
                              { 
                                PrinterSettings = new  PrinterSettings 
                                    { 
                                       PrinterName = "Name"
                                    } 
                               };
                printerStatus = pd.PrinterSettings.IsValid;
            }
            catch (System.Exception ex)
            {
            }

Passing indefinite parameters as Method arguments in C#

One might have a situation where he or she needs to pass a number of variables as arguments at runtime. When we are sure of the parameters required, we can declare them in method signature, like

         public static void PrintMessage(string message, int times)
        {
            for (int i = 0; i < times; i++)
                Console.WriteLine(message);
        }

In the above example we know that we need a message as string and an int (times) which would be used to display the message a number of times. What if we do not know how many variables of some type or different types are required at compile time, like print a number of messages, together or message or names . Here is params keyword which will gracefully tackle this situation. If we need list of argument of particular type, like string

         public static void PringtMessages(params string[] stringsList)
        {
            foreach (string s in stringsList) { }   
            // your logic here
        }

        // this is how to call
        string[] messages = new string[] { "Message1", "Message2" };
        PringtMessages(messages);

This is how, if we a need to pass different type of objects as indefinite number of arguments

        public static void PrintMessageWithID(params object[] list)
        {
            foreach (string s in list) { } 
            // your logic here
        }
        object[] messageAndId = new object[] { "Message1", 1,  "Message2", 2 };
        PrintMessageWithID(messageAndId);