Tuesday, October 14, 2008

How do I convert a string to an int in C#?

Here's an example: using System;

class StringToInt{

public static void Main(){

String s = "105";

int x = Convert.ToInt32(s);

Console.WriteLine(x);

}

}


How do you directly call a native function exported from a DLL?


Here's a quick example of the DllImport attribute in action: using System.Runtime.InteropServices;

class C

{

[DllImport("user32.dll")]

public static extern int MessageBoxA(int h, string m, string c, int type);

public static int Main()

{

return MessageBoxA(0, "Hello World!", "Caption", 0);

}

}

This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.


What is the .NET datatype that allows the retrieval of data by a unique key?

HashTable.


How do you specify a custom attribute for the entire assembly (rather than for a class)?

Global attributes must appear after any top-level using clauses and before the first type or namespace declarations.

An example of this is as follows:

using System;

[assembly : MyAttributeClass]

class X {}

Note that in an IDE-created project, by convention, these attributes are placed inAssemblyInfo.cs.

0 comments: