Home / Archive by category 'C Sharp'

C Sharp

asp-dot-net-c-sharp

Aggregate sum of all elements in array using LINQ

int[] numbers = new int[] {1,2,3,4,5,6,7,8};
 
int result = numbers.Sum();
Console.WriteLine(result);

Set FM Radio frequency in windows phone 7

try
{
	FMRadio myRadio = FMRadio.Instance;
	myRadio.PowerMode = RadioPowerMode.On;
	myRadio.CurrentRegion = RadioRegion.Europe;
	myRadio.Frequency = 91.5;
 
	if (FMRadio.Instance.SignalStrength == 0.0)
	{
	   MessageBox.Show("FM radio cannot run on emulator");
	}
}
catch (Exception ex)
{
  MessageBox.Show("FM Radio has thrown exception" + ex.Message);
}
 
The RadioRegion enumeration only support 3 frequency bands for FM Radio tuning.
1. UnitedStates
2. Japan
3. Europe ( could be used worldwide )

AccelerometerFailedException in windows phone 7

   Accelerometer aSensor = new Accelerometer();
 
   // Add the accelerometer event handler to the accelerometer sensor
   aSensor.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(AccelerometerReadingChanged);
 
   bool isActive = false;
   // Start the accelerometer
   try
   {
      aSensor.Start();
      isActive = true;
   }
   catch (AccelerometerFailedException e)
   {
      // the accelerometer couldn’t be started.  
      isActive = false;
   }
   catch (UnauthorizedAccessException e)
   {
      // This exception is thrown in the emulator-which doesn’t support an accelerometer.
      isActive = false;
   }

State of accelerometer sensor in windows phone 7

There are six possible values for the SensorState enumeration:

  • Disabled
  • Initiating
  • NoData
  • NoPermissions
  • NotSupported
  • Ready

The Accelerometer.Start() method should be called only if the accelerometer is in a ready state. To get the current state, use the Accelerometer.State property.


Reading accelerometer data in windows phone 7

Add a reference to the Microsoft.Devices.Sensors assembly, and declare an instance of the Accelerometer class.
Call the Start() method to generate accelerometer readings.

using Microsoft.Devices.Sensors;
 
Accelerometer accelerometer = new Accelerometer(); 
accelerometer.Start(); 
accelerometer.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(accelerometer_ReadingChanged);

The event handler

void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
  float X = (float)e.X;
  float Y = (float)e.Y;
  float Z = (float)e.Z;
}

Partial class and partial method in C#

Partial class with partial method declaration:

partial class MyPartialClass
{
  ...
  partial void ValidateInput(decimal amount);
}

Partial class with partial method body:

partial class MyPartialClass
{
  ...
  partial void ValidateInput(decimal amount)
  {
    if (amount> 100)
      throw new ArgumentException ("Too Big");
  }
}

Finalizers in C#

Finalizers are class methods that are executed before the garbage collector frees the memory of a referenced object no longer in use. The syntax for a finalizer is the name of the class to which the tilde sign ~ preceeds:

class TestClass1
{
  ~ TestClass1 () {... }
}

The above code is converted by the compiler to the following method declaration:

protected override void Finalize ()
{
  ...
  base.Finalize ();
}

Advantages of Generics in C#

Generics are very useful in C# for storing data and they have the following advantages:
1. Generics allow code reuse for different data types.
2. Generics provide type safety.
3. Generics reduce the number of casting and boxing needed to store value types.


Implementing Stack<T> in C# class

The example below shows how we can implement a generic stack class in c# that can hold upto 100 objects.

public class Stack <T>
{
  int itemposition;
  T[] data = new T[100];
  public void push(T obj)
 {
    data [itemposition++] = obj;
 }
 public T Pop()
 {
    return data [--itemposition];
 }
}

stack<T> collection in c#

An example of stack<T> use in c#:

Stack<int> stack = new Stack <int>();
stack.Push(1);
stack.Push(2);
int x = stack.Pop() / / x is 2
int y = stack.Pop() / / y is 1

Embedded types in C#

An embedded type in C# is declared within the scope of another type.

public class FirstLevel
{
  public class NestedClass {} // embedded Class
  public enum Color {Red, Blue, Tan} // Embedded Enum
}

An embedded type has the following features:
1. The embedded type can access the private members of enclosing type and all other types that the enclosing type has access to.
2. The embedded type can have all possible access modifiers and is not limited to public and internal.
3. The default visibility for an embedded type is private and not internal.
4. Access to an embedded type from outside the enclosing type requires a qualification by the name of the enclosing type (such as when accessing static members).

For example, to access Color.Red from outside our FirstLevel class, we would write the following:

 FirstLevel.Color color = FirstLevel.Color.Red;

All types can be embedded within classes and structs. Embedded types are intensively used by the compiler itself, it generates private classes that manage the state in constructs such as iterators and anonymous methods.


Nullable types in c#

Reference types in c# can have non-existing value with a zero reference. However, For value types this is usually not possible:

string s = null; // OK, reference-type
int i = 0; // compile-time, value-type can not be null

To represent zero in a value type, you need a special construct called Nullable Type . To use a nullable type, the value type is followed by a question mark ?.
Example of nullable type integer:

int?i = 0; // ok since it is nullable type
Console.WriteLine(i == 0) // true

yield break in C#

The yield break instruction specifies that the iterator block is to be abandoned prematurely, without having to add more elements. Below is an example of yield break in c#. A return statement in an iterator block is not allowed therefore you must instead use yield break.

static IEnumerable <string> Foo (bool breakit)
{
  yield return "This One";
  yield return "That One";
 
  if (breakit)
    yield break;
 
  yield return "Another One";
}

Using multiple yield statements in an iterator

static void Main ()
{
  foreach (string s in getty())
    Console.Write (s + " ") // There you go
}
 
static IEnumerable<string> getty()
{
  yield return "There";
   yield return "you";
   yield return "go";
}

Use an iterator to return a sequence of Fibonacci numbers in C#

using System;
using System;
 
class FibTest
{
  static void Main ()
  {
    foreach (int fib in Fibs (6))
      Console.Write (fib + "");
  }
 
  static IEnumerable <int> Fibs (int fibCount)
  {
    for (int i = 0, prevFib = 1, curFib = 1; i <fibCount; i++)
    {
      yield return prevFib;
      int = newFib prevFib curFib +;
      prevFib = curFib;
      curFib = newFib;
    }
  }
}

Output: 1 1 2 3 5 8


Using GetEnumerator to access characters in C# string

Below is an example of using GetEnumerator method of a collection to access characters in a string and display them.

var enumerator = "This is my string".GetEnumerator();
 
while (enumerator.MoveNext())
{
  var element = enumerator.Current ;
  Console.WriteLine (element);
}

What is c# enumerator and enumerable?

An enumerator is a cursor that is read only and moves forward only through a sequence of values.
An enumerator is an object that:
1. Implements IEnumerator
2. Has a method called MoveNext for iterating over the sequence, and a property called Current provides for the reading of the current element of the sequence.

The foreach statement iterates over a enumerable Object. The enumerable object is the logical representation of a sequence and is not itself a cursor.
An enumerable object is an object that:
1. Implements either IEnumerable
2. Has a method called GetEnumerator that returns an enumerator.


Structure of an enumerator in c#

class enumerator    // Implements IEnumerator
{
  public IteratorVariableType Current {get {...}}
  public bool MoveNext () {...}
}
 
class Enumerable    // implements IEnumerable
{
  public Enumerator GetEnumerator () {...}
}

Advantages of call stack during debugging

The call stack can be useful in a number of situations during debugging:
1. The call stack lets us determine when a method is called too early i.e when we invoke the method before the data it requires to function is ready.
2. The call stack helps to determine when a method is called too late i.e after the event is over.
3. The call stack can also help you locate the source of an exception when the exception has been passed up from an underlying class.
4. The call stack also helps to see how the method is called when the method could be called from multiple locations.


Query processes using LINQ to find windows services

IEnumerable<Process> pList = from proc in Process.GetProcesses()
					   where String.Equals(proc.ProcessName, "svchost")
					   select proc;