CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Apr 2014
    Posts
    28

    Showing off my first C# Program! ... And questions?

    I am not new to coding in general, but I am new to C#. I'm versed in the classic VB line of languages (Visual Basic 6, VBScript, ASP), and have dabbled in JavaScript (which is C-like in structure). I'm also well versed in AutoIt.

    Now I'm self-teaching C# to myself. I admit, coming from these other languages, there are a few differences to C# that I've yet to wrap my head around. E.g. Classes, and why the heck I cannot simply #include one source file into another.

    I've written my first C# console program, a Dec-to-Bin converter. I'm sure this has been done many times before, and C# probably has a built-in base conversion function/class. But this was part of my learning process. I'm interested in any constructive comments.
    Code:
    using System;
    
    class MainClass{
        public static void Main(string[] args){
    		//if command line numbers provided, calculate them and exit
    		if(args.Length > 0){
    			foreach(string sNum in args){
    				if(IsNumeric(sNum)){
    					double iNum = Convert.ToDouble(sNum);
    					Console.WriteLine(iNum + " = " + DecToBin(iNum));
    					}else{
    					Console.WriteLine(sNum + " = NaN");
    				}
    			}
    			Environment.Exit(0);
    		}
    		
    		//show about
    		Console.Clear(); //clear screen
    		Console.WriteLine("Decimal > Binary Converter, by Geoff Buchanan, 20140528\n");
    		//ask for user to enter a number
    		bool bStayInLoop = true;
    		while(bStayInLoop){
    			Console.Write("Number to convert (q to quit): ");
    			string sNumToConvert = Console.ReadLine();
    			switch(sNumToConvert){
    				case "q":
    				case "Q":
    					Console.WriteLine("Exitted.");
    					Environment.Exit(0);
    					break;
    				default:
    					if(IsNumeric(sNumToConvert)){
    						double iNumToConvert = Convert.ToDouble(sNumToConvert);
    						Console.WriteLine(DecToBin(iNumToConvert) + "\n");
    					}else{
    						Console.WriteLine("NaN\n");
    					}
    					break;
    			}
    		}
    	}
    	
    	public static string DecToBin(double iDec){
    		double DValue = iDec;
    		string sBinValue = "";
    		
    		//get number of required bits
    		int iBits = 1;
    		while(Math.Pow(2,iBits) <= iDec){iBits++;}
    	 
    		for(int iBitNum=iBits-1;iBitNum>=0;iBitNum--){
    			if(DValue >= Math.Pow(2,iBitNum)){
    				sBinValue = "1" + sBinValue;
    				DValue = DValue - Math.Pow(2,iBitNum);
    			}else{
    				sBinValue = "0" + sBinValue;
    			}
    		}
    		return sBinValue;
    	}
    	 
    	public static bool IsNumeric(string n){
    		double dn; //container for returned double value of n
    		return double.TryParse(n,out dn);
    	}
    }
    I am very function oriented. I have built libraries of functions in multiple other languages (as I'm sure most of you have). I want to understand this: Apparently there is no such thing as a code include in C#, which honestly, baffles me. Therefore, if I want to break my code into includes (e.g. the DecToBin() and IsNumeric() functions to their own source files), I can't. As far as I can tell, if I'm not using VS Express, I can't split my files? Maybe I'm not understanding.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Showing off my first C# Program! ... And questions?

    There are many options:
    1) partial classes (splits the class up across different files)

    mainclass.cs
    Code:
    using System;
    
    partial class MainClass{
        public static void Main(string[] args){
    		//if command line numbers provided, calculate them and exit
    		if(args.Length > 0){
    			foreach(string sNum in args){
    				if(IsNumeric(sNum)){
    					double iNum = Convert.ToDouble(sNum);
    					Console.WriteLine(iNum + " = " + DecToBin(iNum));
    					}else{
    					Console.WriteLine(sNum + " = NaN");
    				}
    			}
    			Environment.Exit(0);
    		}
    		
    		//show about
    		Console.Clear(); //clear screen
    		Console.WriteLine("Decimal > Binary Converter, by Geoff Buchanan, 20140528\n");
    		//ask for user to enter a number
    		bool bStayInLoop = true;
    		while(bStayInLoop){
    			Console.Write("Number to convert (q to quit): ");
    			string sNumToConvert = Console.ReadLine();
    			switch(sNumToConvert){
    				case "q":
    				case "Q":
    					Console.WriteLine("Exitted.");
    					Environment.Exit(0);
    					break;
    				default:
    					if(IsNumeric(sNumToConvert)){
    						double iNumToConvert = Convert.ToDouble(sNumToConvert);
    						Console.WriteLine(DecToBin(iNumToConvert) + "\n");
    					}else{
    						Console.WriteLine("NaN\n");
    					}
    					break;
    			}
    		}
    	}
    	
    }
    mainclass.utility.cs (note: the separate file that the partial class is in doesn't have to follow any file naming conventions).
    Code:
    using System;
    
    partial class MainClass{
    	public static string DecToBin(double iDec){
    		double DValue = iDec;
    		string sBinValue = "";
    		
    		//get number of required bits
    		int iBits = 1;
    		while(Math.Pow(2,iBits) <= iDec){iBits++;}
    	 
    		for(int iBitNum=iBits-1;iBitNum>=0;iBitNum--){
    			if(DValue >= Math.Pow(2,iBitNum)){
    				sBinValue = "1" + sBinValue;
    				DValue = DValue - Math.Pow(2,iBitNum);
    			}else{
    				sBinValue = "0" + sBinValue;
    			}
    		}
    		return sBinValue;
    	}
    	 
    	public static bool IsNumeric(string n){
    		double dn; //container for returned double value of n
    		return double.TryParse(n,out dn);
    	}
    }

  3. #3
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Showing off my first C# Program! ... And questions?

    2) Separate classes
    mainclass.cs
    Code:
    using System;
    
    partial class MainClass{
        public static void Main(string[] args){
    		//if command line numbers provided, calculate them and exit
    		if(args.Length > 0){
    			foreach(string sNum in args){
    				if(Utility.IsNumeric(sNum)){
    					double iNum = Convert.ToDouble(sNum);
    					Console.WriteLine(iNum + " = " + Utility.DecToBin(iNum));
    					}else{
    					Console.WriteLine(sNum + " = NaN");
    				}
    			}
    			Environment.Exit(0);
    		}
    		
    		//show about
    		Console.Clear(); //clear screen
    		Console.WriteLine("Decimal > Binary Converter, by Geoff Buchanan, 20140528\n");
    		//ask for user to enter a number
    		bool bStayInLoop = true;
    		while(bStayInLoop){
    			Console.Write("Number to convert (q to quit): ");
    			string sNumToConvert = Console.ReadLine();
    			switch(sNumToConvert){
    				case "q":
    				case "Q":
    					Console.WriteLine("Exitted.");
    					Environment.Exit(0);
    					break;
    				default:
    					if(Utility.IsNumeric(sNumToConvert)){
    						double iNumToConvert = Convert.ToDouble(sNumToConvert);
    						Console.WriteLine(DecToBin(iNumToConvert) + "\n");
    					}else{
    						Console.WriteLine("NaN\n");
    					}
    					break;
    			}
    		}
    	}
    	
    }
    utility.cs
    Code:
    using System;
    
    class Utility{
    	public static string DecToBin(double iDec){
    		double DValue = iDec;
    		string sBinValue = "";
    		
    		//get number of required bits
    		int iBits = 1;
    		while(Math.Pow(2,iBits) <= iDec){iBits++;}
    	 
    		for(int iBitNum=iBits-1;iBitNum>=0;iBitNum--){
    			if(DValue >= Math.Pow(2,iBitNum)){
    				sBinValue = "1" + sBinValue;
    				DValue = DValue - Math.Pow(2,iBitNum);
    			}else{
    				sBinValue = "0" + sBinValue;
    			}
    		}
    		return sBinValue;
    	}
    	 
    	public static bool IsNumeric(string n){
    		double dn; //container for returned double value of n
    		return double.TryParse(n,out dn);
    	}
    }

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Showing off my first C# Program! ... And questions?

    3) Separate classes

    Same as 2), but the Utility class would be in a different class library.

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Showing off my first C# Program! ... And questions?

    Lastly, you may consider following the C# styling convention. At first, it might seem odd given that you have programmed in other languages, but it's helpful to folks that are used to a particular language if you follow the styling guidelines for that language.

    In C#, typically...
    Braces start on a new line
    Class names, method names and properties are PascalCased.
    Method parameters and local variables are camelCased.
    Class fields (when used are camelCased and usually start with an '_').
    Variables don't include Hungarian Notation prefixes.

    Code:
    using System;
    
    class Utility
    {
      public static string DecToBin(double dec)
      {
        double value = dec;
        string binValue = "";
    		
        //get number of required bits
        var bits = 1;
    
        while(Math.Pow(2,bits) <= dec)
        {
          bits++;
        }
    	 
        for(var bitNum= bits - 1; bitNum >= 0; bitNum--)
        {
          if(value >= Math.Pow(2, bitNum))
          {
              binValue = "1" + binValue;
              value = value - Math.Pow(2, bitNum);
          }
          else
          {
            binValue = "0" + binValue;
          }
        }
        return binValue;
      }
    	 
      public static bool IsNumeric(string n)
      {
        double dn; //container for returned double value of n
        return double.TryParse(n,out dn);
      }
    }

  6. #6
    Join Date
    Apr 2014
    Posts
    28

    Re: Showing off my first C# Program! ... And questions?

    Thank you. Very good info. I was able to split my code into multiple files and compile with csc. Woohoo!

  7. #7
    Join Date
    Apr 2014
    Posts
    28

    Re: Showing off my first C# Program! ... And questions?

    Quote Originally Posted by Arjay View Post
    Lastly, you may consider following the C# styling convention. At first, it might seem odd given that you have programmed in other languages, but it's helpful to folks that are used to a particular language if you follow the styling guidelines for that language.

    In C#, typically...
    Braces start on a new line
    Class names, method names and properties are PascalCased.
    Method parameters and local variables are camelCased.
    Class fields (when used are camelCased and usually start with an '_').
    Variables don't include Hungarian Notation prefixes.
    I agree. I wasn't aware of the specific C# conventions.
    The only one I really have an argument with is the Hungarian Notation. Other than "it's not standard", I can't think of a reason not to use it. That one letter helps me as the code reader determine quickly what the type is intended to be, rather than having to muddle back and forth in the code. But that's just me, whining. :P

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Showing off my first C# Program! ... And questions?

    Quote Originally Posted by SlowCoder74 View Post
    I agree. I wasn't aware of the specific C# conventions.
    The only one I really have an argument with is the Hungarian Notation. Other than "it's not standard", I can't think of a reason not to use it. That one letter helps me as the code reader determine quickly what the type is intended to be, rather than having to muddle back and forth in the code. But that's just me, whining. :P
    I used to feel the same way, but how often do you really look at code outside the IDE (like in code printed on paper)? If you are like me, probably not much and if you are in the IDE looking at code, then you can find the type by hovering over the variable or by right-clicking and choosing "Go to Declaration". You might find that once you get used to the non-Hungarian notation, you don't miss it (and find the code is less cluttered).

    That being said, you might have noticed that I slipped in the use of 'var' in there.

    Rather than something like:
    Code:
    int bits = 1;
    with var, it's:
    Code:
    var bits = 1;
    Coming from a C++ background, it took some getting used to because I kept thinking it was the generic object like in VB (or at least in the VB that I used). It's actually different in that, in C# var is type safe. So you can't declare a variable a certain type and then change it. The following isn't allowed:
    Code:
    var bits = 1;
    bits = "different type"; // compiler error
    Of course using var in the simple case above doesn't really show off how readable the code can become. Where it really shines is when using generics:

    Say I have a generic dictionary that maps a guid to a person object. Rather than typing:
    Code:
    Dictionary<Guid, Person> peopleLookup = new Dictionary<Guid, Person>();
    I can type
    Code:
    var peopleLookup = new Dictionary<Guid, Person>();
    I found that I quickly got used to seeing var (and not missing the explicit declarations).

    In general, I usually code with IDE add-in tool and follow the code naming/styling recommendations of the tool.

    I use ReSharper and generally get my code to compile without any ReSharper errors or warnings (and the rest falls into place).

  9. #9
    Join Date
    Apr 2014
    Location
    in northeast ohio
    Posts
    94

    Re: Showing off my first C# Program! ... And questions?

    though i don't use the command line myself in C# i use vs
    i used to with java quite a bit, c# takes a lot from java and c++
    java uses something similar packages but in c# its namespaces and the #using directive
    in fact c# is extremely similar to java and to learn one is almost like learning both.
    E.g. Classes, and why the heck I cannot simply #include one source file into another.
    what your really talking about here is namespaces and how they relate
    http://tutorials.csharp-online.net/C...is_a_namespace

    #using System; // just like include your including the system namespace here
    for instance the system namespace contains many class's these can be consider separate files

    http://msdn.microsoft.com/en-us/library/78f4aasd.aspx
    csc /defineEBUG /optimize /out:File2.exe *.cs

    // file one.cs
    #using System;
    namespace mynamespace
    {
    public class program{ ... ect...}
    public class B{ A a = new A(); }
    }
    // file two.cs
    #using System;
    namespace mynamespace
    {
    public class A{}
    }

    you might want to bookmark this for reference
    http://tutorials.csharp-online.net/C..._Specification
    http://www.microsoft.com/en-us/downl...s.aspx?id=7029
    Last edited by willmotil; May 29th, 2014 at 09:38 PM.

  10. #10
    Join Date
    Apr 2014
    Posts
    28

    Re: Showing off my first C# Program! ... And questions?

    You guys have provided some very good information to help me get started. Thank you!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured