by Joel Limardo
Home | Twitter | LinkedIn | Consulting | About | RSS | Map
Areas:
Process
 
Technical
 
Projects:


Tue, 10 Jan 2017

.NET Projects

  1. Read ILSpy - Assembly Browser/Decompiler(Windows)
  2. Initial Mono vs. CSharp Shell
  3. Simple Casting
  4. While Loop
  5. For Loop
  6. Switch
  7. Arrays
  8. Objects
  9. Namespaces
  10. Static Methods
  11. Numeric Input
  12. MonoDevelop
  13. Passing Arguments
  14. Variable Arguments
  15. DateTime
  16. Inheritance
  17. Nullable Types
  18. Anonymous Types


posted at: 22:47 | path: /technical/programming/DOTNET | this entry | top

Nullable Types

csharp> int? m = null;
csharp> int p = null;
(1,10): error CS0037: Cannot convert null to 'int' because it is a value type
csharp> int y = m?? - 1;
csharp> y
-1

Strange syntax for nullable types (question mark) and even stranger when you try to use them (double quotes).



posted at: 22:43 | path: /technical/programming/DOTNET | this entry | top

Anonymous Types

csharp> var v = new {Amount=100 , Message="hi"};
csharp> v.Amount;
100
csharp> v.Message; 
"hi"
csharp> v.Amount = 999;
(1,4): error CS0200: Property or indexer `anonymous type.Amount' cannot be assigned to (it is read-only)

So anonymous types are useful for holding a bunch of read-only values together.



posted at: 15:18 | path: /technical/programming/DOTNET | this entry | top

Initial Mono vs. CSharp Shell

With the Mono kit there is a 'Mono shell' that can be run from the command line like this:

 csharp

It produces some output like this:

 csharp> string sFahr = "88";
 csharp> print ((Int32.Parse(sFahr) - 32) * (5.0/9.0)); 
 31.1111111111111
 csharp> print ((Int32.Parse(sFahr) - 32) * (5/9));     
 0
 csharp> print ((Int32.Parse(sFahr) - 32) * (5.0/9.0));
 31.1111111111111

It works with standard C#:

using System;
 class celsius 
 { public static int Main(string[] args){
      Console.Write("Enter temp in degrees Farenheit:");
      string sFahr = Console.ReadLine();
      double dFahr  = double.Parse(sFahr);
      double dCelsius;
      //dCelsius = (dFahr - 32.0) * (5.0 / 9.0) ;
      dCelsius = (dFahr - 32.0) * (5/9) ; 
      Console.WriteLine("Temperature in degrees Celsius = " + dCelsius );
      return(0);
 }
 }

Because it works the same way you can try out syntax and run all sorts of tests with it. There's even a way to run it in standalone scripts (see the manpage).

Update #1: You have to give sFahr (variable above) a type or csharp will issue an error.



posted at: 15:04 | path: /technical/programming/DOTNET | this entry | top


Sat, 05 Sep 2015

Interfaces

The weird thing is that you can declare variables using interfaces and then make them refer to actual objects, like so:

 namespace InterfaceTest {
     using System;
     public interface IProduct {
          void Stock();
          void ReStock();
     }
     public class UsesInterface : IProduct {
          public int someCounter;
          public UsesInterface(){
               this.someCounter = 0;
          }
     public void Stock() { 
              Console.WriteLine("in stock\n");
          }
          public void ReStock() {
              Console.WriteLine("in restock\n");
          }
     }
 }
csharp> using InterfaceTest;
csharp> LoadAssembly("./Interface.dll");
csharp> using InterfaceTest; 
csharp> IProduct tp = new UsesInterface(); csharp> tp.Stock(); in stock csharp> tp.ReStock(); in restock csharp> UsesInterface us = new UsesInterface(); csharp> (1 == 1) ; true csharp> (us is IProduct); true


posted at: 13:44 | path: /technical/programming/DOTNET | this entry | top


Wed, 02 Sep 2015

Inheritance

 namespace Structures {
      public class Building {
          /* protected -- doesn't work */ public string name;
          public Building() {
               this.name= "";
          }
      }
 }

 namespace Structures {
      public class House : Building {
           public House(string aName) 
           {
                base.name = aName;
           }
      }
 }

You could compile these separately but why bother:

gmcs -out:Structures.dll -t:library Building.cs House.cs

I had to reference 'base' in order to access the base class' name property for some reason. All of the simple examples seem to assume you won't be defining a namespace across different files, but that is a load of nonsense. After a while a single file is going to be enormous.

 csharp> LoadAssembly("Structures.dll");
 csharp> using Structures;
 csharp> House h = new House("M");
 csharp> h.name;

Also, the documentation claims that the protected properties of the base class will be available to the child class but that just generated an error for me in the above case so I had to change it to public.



posted at: 20:52 | path: /technical/programming/DOTNET | this entry | top


Tue, 01 Sep 2015

DateTime

Code Example: Pendulum class.

Here we are using not only the DateTime class but the TimeSpan class for intervals. If I was running tick() on a timer the getTimeStamp() method would tell me the last time it successfully ran.

  csharp> LoadAssembly("./Pendulum.dll");
  csharp> using TimedObjects;
  csharp> Pendulum p = new Pendulum(120);
  csharp> p.tick();
  csharp> p.isInFailedState();
  false
  csharp> p.isInFailedState();
  false
  csharp> p.tick();
  csharp> p.isInFailedState();
  false
  ...
  csharp> p.tick();
  csharp> p.isInFailedState();
  true
  csharp> p.getTimeStamp().ToString();
  "9/1/2015 9:25:35 PM"
  csharp> DateTime.Now.ToString();
  "9/1/2015 9:28:13 PM"


posted at: 21:53 | path: /technical/programming/DOTNET | this entry | top


Mon, 31 Aug 2015

Variable Number of Arguments

 namespace Soup {
 //..
    public int addItUp(params int[] Nums)
    {
       int Total = 0;
       foreach (int n in Nums) {
           Total += n;
       }
       return (Total);
    }
 //..
 csharp> string [] s = {};
 csharp> Can c = new Can(s);
 csharp> print (c.addItUp(4,3,2,2));
 11
 csharp> print (c.addItUp(4,3,2,1)); 
 10
 csharp> print (c.addItUp(2,4,6,8,10));


posted at: 21:43 | path: /technical/programming/DOTNET | this entry | top

Out Arguments

It is weird but when you want to modify an argument you have to declare your intent in the method itself and when you make the call...

 
    public class Can {
     //..
     public void openCan(out string didIt){
         didIt = "yes, I did it";
     //..
    csharp> LoadAssembly("/tmp/Can.dll");
    csharp> using Soup;
    csharp> string [] dummy = {};
    csharp> Can c = new Can(dummy);
    csharp> string initialValue = "something I have";
    csharp> c.openCan(initialValue);
     {interactive}(1,4): error CS1502: The best overloaded method match for Soup.Can.openCan(out string)' has some invalid arguments...Argument#1' is missing `out' modifier
    csharp> c.openCan(out initialValue);
    csharp> print (initialValue);
    yes, I did it


posted at: 21:25 | path: /technical/programming/DOTNET | this entry | top

Passing Arguments

When using a scripting language you can simply pass a reference to an array. In CSharp you have to tell the method that you are intending to pass an array:

 namespace Soup {
    using System;
     public class Can {
         public Can(string []manufacturers) { 
              foreach(string manu in manufacturers) {
                   Console.Write(manu + "\n");
              }
         }
     }
 }
 csharp> LoadAssembly("/tmp/Can.dll");
 csharp> using Soup;
 csharp> string [] manufacturers = {"Progresso","Campbells","Aldi Brand"};
 csharp> Can c = new Can(manufacturers);
 Progresso
 Campbells
 Aldi Brand


posted at: 20:58 | path: /technical/programming/DOTNET | this entry | top

Numeric Formatting

There is a whole list of things you can do to modify number formats. It is a bit like printf in other languages.

csharp> string p = String.Format("{0} is {1}",24,24); 
csharp> print (p); 
24 is 24
csharp> string p = String.Format("{0:C} is {1}",24,24);
csharp> print (p);
$24.00 is 24
csharp> string p = String.Format("{0:C} is {1:X}",24,24);
csharp> print (p); 
$24.00 is 18 csharp> string p = String.Format("{0:C} is {1:##0.0#}",24,24); csharp> print (p);
$24.00 is 24.0


posted at: 19:26 | path: /technical/programming/DOTNET | this entry | top

Dealing with Numeric Input

The data types make dealing with string input and converting it much more annoying than scripting languages. Getting familiar with the various static methods of core classes helps.

      // Scan through the SSN to prove it has numbers
      public static bool hasNumbersInRightPlaces ( string SSN ) {
           int SSNLength = SSN.Length;
           bool isGood = true;
           for (int i=0; i<= SSNLength - 1; i++) {
                if ((i == 3) || (i == 6)) {continue; }

                if (Char.IsDigit(SSN[i]) == false)
                {
                     isGood = false;
                }
           }
           return (isGood);
      }


csharp> LoadAssembly("./Student.dll");
csharp> using AnExample;
csharp> Student s = new Student("11a-aa-1111");
csharp> Describe (s);
"public class Student {
...
csharp> Student.hasNumbersInRightPlaces(s.SSN);
false
csharp> Student s = new Student("111-11-1111"); 
csharp> Student.hasNumbersInRightPlaces(s.SSN); true


posted at: 19:25 | path: /technical/programming/DOTNET | this entry | top

MonoDevelop

It is annoying but there doesn't appear to be a ILSpy in the Mono kit I'm using. I'm using:

 Mono JIT compiler version 2.10.8.1 (Debian 2.10.8.1-8)

Perhaps this is old. At any rate, in order to view inside of assemblies you can use MonoDevelop, expand to see the References folder in the left-hand side treeview, and right click. Choose Edit References, click on the .Net Assembly tab and search around for your assembly. Use the Add button at the bottom to add it to the current project. After this you can use the View->Assembly Browser to view the assembly innards.



posted at: 19:04 | path: /technical/programming/DOTNET | this entry | top


Sun, 30 Aug 2015

Namespaces

If you place your class in a namespace you'll have to use the Using keyword to obtain access to it in the shell.


     namespace AnExample {
     using System;
     public class Student {
          protected string SSN;

          public Student (string SSN) {
                this.SSN = SSN;
          }

      }
    }

Now in the shell:

csharp> LoadAssembly("./Student.dll"); 
csharp> using AnExample;
csharp> ShowUsing();
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using AnExample;
csharp> Student s;
csharp> Describe (s);
"<null>"
csharp> Student s = new Student("555-55-5555");

If you didn't do this you would have to preface the class with the namespace like this:

 AnExample.Student s = new AnExample.Student("555-55-5555");


posted at: 22:11 | path: /technical/programming/DOTNET | this entry | top

Objects

The shell doesn't let you define classes so you'll have to compile them into assemblies and then load them:

 gmcs foo.cs -t:library

 csharp> LoadAssembly("/tmp/foo.dll");
 csharp> foo theFoo;
 csharp> theFoo = new foo();
 csharp> Describe(theFoo);
 "public class foo {
      public foo ();
           public string sayFoo ();
      }
 "
 csharp> theFoo.sayFoo();
 "FOOOOO"

The Describe() method normally just shows the contructors and method names so it is useful for picking out a method to use.



posted at: 15:42 | path: /technical/programming/DOTNET | this entry | top

Static Methods

Some methods belong to the class itself. No class instantiation needs to be done and they cannot reference 'this' internally (because there is no object reference).

 namespace AnExample {
      //... details removed for brevity
      public Student (string SSN) {
           if (Student.isCorrectSSN(SSN))
           { 
                this.SSN = SSN;
           } else {
                this.SSN = null;
           }
      }

  public static bool isCorrectSSN(string SSN) {

       bool isOkay = true;

       if ( (SSN.IndexOf("-") < 0 ) ||
            (SSN.Length != 11) ) {
            isOkay = false;
       } 
       return ( isOkay );
//...



posted at: 15:40 | path: /technical/programming/DOTNET | this entry | top


Sat, 29 Aug 2015

While Loop

 csharp> while (n > 0) { print ("the value is " + n ); n--; }
the value is 10 the value is 9 the value is 8 // ... the value is 1


posted at: 23:50 | path: /technical/programming/DOTNET | this entry | top

For Loop

 csharp> for (int n = 1; n >= 10; n = n + 1) { print (n); }
// Returns nothing csharp> for (int n = 1; n <= 10; n = n + 1) { print (n); } 1 2 3 // ... 10

Remember that the for loop condition says, 'do this while this statement returns true.'



posted at: 23:50 | path: /technical/programming/DOTNET | this entry | top

If/Then

 csharp> bool a = true;
csharp> if (a) { print("it is true") } else { print ("it is false") }; {interactive}(1,30): error CS1525: Unexpected symbol `}', expecting `;' {interactive}(1,61): error CS1525: Unexpected symbol `}', expecting `;' csharp> if (a) { print("it is true"); } else { print ("it is false"); } it is true csharp> a = false; csharp> if (a) { print("it is true"); } else { print ("it is false"); } it is false


posted at: 23:49 | path: /technical/programming/DOTNET | this entry | top

Arrays

 csharp> int[] mArr = new int[5];                                          
csharp> for (int i = 0; i <= 4; i++) { mArr[i] = i * 3; print (mArr[i]);} 0 3 //.. 12 csharp> int []mArr = {1*9,2*9, 3*9, 4*9, 5*9, 6*9}; csharp> for (int i = 0 ; i <= 5; i++) { print (mArr[i]); } 9 18 //.. 54 csharp> foreach (int item in mArr) { print (item); } 9 /.. 54

Multi-dimensional:

int[] m = System.Int32[]
int[,] p = System.Int32[,]
char[,] pg = System.Char[,]


posted at: 15:15 | path: /technical/programming/DOTNET | this entry | top

Switch Statement

 csharp> switch(it) {
> case true : > print ("it is true"); > break; > case false: > print ("It is false"); > break; > default: > print ("no idea"); > break; > }


posted at: 14:49 | path: /technical/programming/DOTNET | this entry | top

Simple Casting

 csharp> long lVal = 1000;
csharp> int sf; csharp> sf = lVal; {interactive}(1,5): error CS0266: Cannot implicitly convert type `long' to `int'. An explicit conversion exists (are you missing a cast?) csharp> sf = (int)lVal; csharp> print (sf); 1000


posted at: 14:26 | path: /technical/programming/DOTNET | this entry | top

© 2015-2017. All Rights Reserved. All original code appearing on this site is MIT Licensed unless otherwise noted.