Windows Phone Developers

Tuesday, November 25, 2008

Output Parameters in C# (.NET)


An output parameter is declared with the out modifier.

private static void ParamExample(double radius, out double Area, out double Perimeter)

{

const double pi = 22/7;

Area = pi * radius * radius;

Perimeter = 2 * pi * radius;

}

It is similar to a reference parameter except that the initial value of the caller-provided argument is unimportant.

double rad = 10.0;

double area;

double pm;

ParamExample(rad, out area, out pm);

Console.WriteLine("For a circle of radius {0} : Area is {1} and Perimeter is {2}", rad, area, pm);




output parameter in .NET


See also

How to get the return value from C# program (console application)

Command Line Arguments in C#

How to Return Multiple Values from a VBA Function


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Readonly Fields in C# / Readonly Properties in C#

Read-only fields can be declared with a readonly modifier.

class Company

{

public static readonly string CompanyName = "VBADUD Inc";

}

Assignment to a readonly field can only occur as part of the field’s declaration or in a constructor in the same class.

class Company

{

// Assignment of Readonly value in Field declaration

public static readonly string CompanyName = "VBADUD Inc";

// Assignment of Readonly value in a static constructor

static Company()

{

CompanyName = "My Name";

}

}

Assigning the value to a readonly field outside the class will throw the following error:

Company.CompanyName = "My Company";

A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to Get Remainder of a division using C# (.NET)

C# (.NET) Code to find odd / even numbers

In Visual Basic, Mod Function (x MOD Y) is used to get the remainder of a division. Similarly x % y is used to get the remainder in C#

public static void remainder()

{

short rem = 51 % 5;

Console.WriteLine(rem);

try

{

short input = System.Convert.ToInt16(Console.ReadLine());

if (input % 2 == 0)

{

Console.WriteLine("Even number");

}

else

{

Console.WriteLine("Odd Number");

}

}

catch (FormatException ex1)

{

Console.WriteLine("Please enter numerals only");

}

}


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Insert Array to Excel Range using VSTO

Copy Array Values to Excel Range using VSTO

Many times we need to insert text to a contiguous Excel range using VSTO (like column headings). The following code does exactly that

private void InsertHeading()

{

string[] Header = { "Sno", "Product Code", "Product Name", "Quanity", "Price", "Total" };

Excel.Worksheet sht = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

Excel.Range myHeader = sht.get_Range("A1", "F1");

myHeader.Value2 = Header;

myHeader.Columns.AutoFit();

}


See Also

How to use .Net Array.Sort Function in VBA

Convert Dates to Arrays using Array Function

Object Arrays in C# using Indexers

Insert CSV File to Array using C#

Creating and Sorting Arrays in C#

Split Function in Visual Basic .Net

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

How to call a VSTO Addin Function from VBA

Call Method in Addin from Visual Basic Applications

VSTO Addins we write might contain good number of reusable components. The following article shows how to use them from external applications. This consists of the following steps:

1. Creating a VSTO Addin with a public method

2. Expose the VSTO Method for external use

3. Consume the VSTO Method from VBA

Creation of VSTO Excel Addin

Create a new project from Visual Studio - - > Office Projects - - > Excel 2007 Addin and call the project CallVSTOExample

This will automatically create necessary references and add required directives


VSTO Addin



using System;

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;

Create a new C# Class module and add the following code to it

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;

namespace CallVSTOExample

{

[ComVisible(true)]

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]

public interface IAddinVSTO

{

void SayHello();

}

[ComVisible(true)]

[ClassInterface(ClassInterfaceType.None)]

public class VSTOExample : IAddinVSTO

{

#region IAddinVSTO Members

public void SayHello()

{

Excel.Worksheet wks = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

Excel.Range myRange = wks.get_Range("A1", System.Type.Missing);

myRange.Value2 = "Hello";

}

#endregion

}

}

Here we have created one interface and have also created a class that implements the interface. The class has a simple method SayHello, which inserts “Hello” in cell A1 of active worksheet

The class must be public and should expose the IDispatch interface for it to be visible to COM

InterfaceIsIDispatch indicates an interface is exposed to COM as a dispinterface, which enables late binding only.

Exposing the method for external use

Add the following code to ThisAddin class

private VSTOExample utilities;

protected override object RequestComAddInAutomationService()

{

if (utilities == null)

utilities = new VSTOExample();

return utilities;

}

RequestComAddInAutomationService method returns an object in your add-in that can be used by other Microsoft Office solutions.

Override this method to expose an object in your add-in to other Microsoft Office solutions. This includes other add-ins and document-level customizations running in the same application process, VBA code, and external automation code.

The object that you return must be public, it must be visible to COM, and it must expose the IDispatch interface. If the object you return does not meet these requirements, the Visual Studio Tools for Office runtime will throw an InvalidCastException after it calls your implementation.

Compile the code and open the application (Excel) with the addin installed.

Excel VBA Code to call VSTO Method

The VSTOAddin that was created will be loaded as a COMAddin in Excel. The following code will retrieve the addin information

Sub Execute_VSTO_Addin_Macro()

Dim oAddin As COMAddIn

Dim oCOMFuncs As Object

Set oAddin = Application.COMAddIns("CallVSTOExample")

Set oCOMFuncs = oAddin.Object

oCOMFuncs.SayHello

End Sub

The Object property returns the object represented by the specified COMAddIn object. The VSTO function SayHello is called using the COMAddin’s object as shown above

See Also

How to use .Net Array.Sort Function in VBA

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Property, indexer, or event 'Range' is not supported by the language; try directly calling accessor method 'Microsoft.Office.Interop.Excel._Worksheet.

A worksheet Range cannot be called directly as shown below

Excel.Worksheet wks = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

wks.Range("A1").value2 = "Hi";

Instead use the get_Range Method of Worksheet Class

Excel.Worksheet wks = Globals.ThisAddIn.Application.ActiveSheet as Excel.Worksheet;

0020Excel.Range myRange = wks.get_Range("A1", System.Type.Missing);

myRange.Value2 = "Hello";

See also :

Object Arrays in C# using Indexers

Properties in .NET / Get and Set Methods in .NET


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

The type or namespace name 'ComVisible' could not be found (are you missing a using directive or an assembly reference?)

The type or namespace name 'ComVisibleAttribute' could not be found (are you missing a using directive or an assembly reference?)

This error occurs when you are trying to use ComVisibleAttribute in a class without a reference to System.Runtime.InteropServices namespace

[ComVisible(true)]

public interface IAddinVSTO

{

void SayHello();

}

Should have a reference to System.Runtime.InteropServices namespace like shown below

using System.Runtime.InteropServices;

[ComVisible(true)]

public interface IAddinVSTO

{

void SayHello();

}




ComVisibleAttribute Error Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

What are assemblies in C#?

A C# assembly is the compiled output of the program. An assembly is the tangible output of a program, which might be an executable (.exe) or a library (.dll).

The output type of a C# program can be specified in Visual Studio or through command prompt

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Saturday, November 15, 2008

How to Override methods in C#

Overriding functions in C#

Methods from base class can be overridden in the derived class and customized for necessity. This means the derived class can contain the member with the same name as that of the parent class

To override a method in the derived class :

  • The base class method must be defined virtual
  • Method in the derived class should be preceded by new or override keywords
  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.
  • If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.
  • The base class method can be called from within the derived class using the base keyword.
  • The override, virtual, and new keywords can also be applied to properties, indexers, and events.

class BaseClass

{

virtual public string SayHi()

{

return( "Hi");

}

}

class DerivedClass : BaseClass

{

public override string SayHi()

{

return (base.SayHi() + " from derived");

}

}

If the base class is not declared as virtual, abstract or override, the compiler throws the following error:

'function1' : cannot override inherited member 'function2' because it is not marked "virtual", "abstract", or "override"

A method was overridden that was not explicitly marked as virtual, abstract, or override.

On the other hand, If the override or new keyword is missing the following error will occur

'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.

A variable was declared with the same name as a variable in a base class. However, the new keyword was not used. This warning informs you that you should use new; the variable is declared as if new had been used in the declaration.

How to access the method in a base class from the derived class

base keyword is used to access members of the base class from within a derived class

return (base.SayHi() + " from derived");

calls the SayHi method of the base class

,

How to override functions in .NET, .NET Function overriding, .NET how to access base class’s method in derived class, base keyword in .NET, virtual methods in .NET, Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Type Inference in C# using var keyword

Implicitly Typed Local Variables in C#

Instead of explicitly declaring the variable of a particular type (int, short, string etc), one can define a variable of type ‘var’ and allowing the compiler to infer the type

For example,

var i = 10;

is equivalent to

int i = 10;

The inferred type may be a built-in type, an anonymous type, a user-defined type, a type defined in the .NET Framework class library, or any expression.

Implicit Typed Variables in .NET, .NET Variant, Var keyword in .NET, Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Access Modifiers Comparison in Visual Basic .NET (VB.NET)

Keywords that specify access level are called as Access Modifers (e.g., Private, Public, Friend etc). Comparison of access levels of different keywords is given below:

Access modifier

Access level granted

Elements you can declare with this access level

Declaration context within which you can use this modifier

public

Unrestricted:

Any code that can see a public element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

protected

Derivational:

Code in the class that declares a protected element, or a class derived from it, can access the element

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

internal

Assembly:

Code in the assembly that declares an Internal element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

protectedinternal

Union of Protected and Internal:

Code in the same class or the same assembly as a protected Internal element, or within any class derived from the element's class, can access it

The protectedinternal accessibility means protected OR internal, not protected AND internal. In other words, a protectedinternal member is accessible from any class in the same assembly, including derived classes. To limit accessibility to only derived classes in the same assembly, declare the class itself internal, and declare its members as protected.

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

private

Declaration context:

Code in the type that declares a private element, including code within contained types, can access the element

Interfaces

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Access Modifiers Comparison in Visual Basic .NET (VB.NET)

Keywords that specify access level are called as Access Modifers (e.g., Private, Public, Friend etc). Comparison of access levels of different keywords is given below:

Access modifier

Access level granted

Elements you can declare with this access level

Declaration context within which you can use this modifier

Public

Unrestricted:

Any code that can see a public element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

Protected

Derivational:

Code in the class that declares a protected element, or a class derived from it, can access the element

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

Friend

Assembly:

Code in the assembly that declares a friend element can access it

Interfaces

Modules

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Source file

Namespace

Interface

Module

Class

Structure

ProtectedFriend

Union of Protected and Friend:

Code in the same class or the same assembly as a protected friend element, or within any class derived from the element's class, can access it

Interfaces

Classes

Structures

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates

Class

Private

Declaration context:

Code in the type that declares a private element, including code within contained types, can access the element

Interfaces

Classes

Structures

Structure members

Procedures

Properties

Member variables

Constants

Enumerations

Events

External declarations

Delegates


Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

Destructors in C# (.NET)

Unlike constructors, destructors are sparsely used in C# programs. This is because .NET Framework does an excellent job of memory management using garbage collection. However, it there are too many unmanaged resources in the application, they can be used as follows

class ClsTea : IRetail

{

//Variables

private string _locale;

private static string _brand;

// Class Destructor

~ ClsTea()

{

Console.WriteLine("Destructor Called");

// Code to release objects

}

// Class Default Constructor

public ClsTea()

{

Console.WriteLine("Constructor Called");

_brand = "N/A";

}

  • A class can only have one destructor.
  • Destructors cannot be inherited or overloaded.
  • Destructors cannot be called. They are invoked automatically.
  • A destructor does not take modifiers or have parameters.

Destructors in .NET, .NET Destructors, How to create a destructor in .NET, How to use destructors in .NET,

See also

How to create and use Static Constructors in C# (.NET)

How to create Default Constructors in C#

What is an Abstract Class / Abstract Classes in C#

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

kbAlertz.com :: Visual Studio 2005

kbAlertz.com :: Visual Studio 2008

kbAlertz.com :: Visual Basic 2005