Sei sulla pagina 1di 7

1

1. Is C# / VB.NET type safe? Can CLR Handle type unsafe languages? How it is done? Yes both c# and vb.net are type safe. C# support unsafe code but vb.net does not. Advantages of Unsafe Code in C#: Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible. Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. Or third parties may supply DLLs that some of its functions need pointer parameters. Although this can be done by writing the DLLImport declaration in a way that avoids pointers, but in some cases it?s just much simpler to use pointer. Memory Addresses, there is no way to know the memory address of some data without using pointers. Disadvantages of Unsafe Code in C#: Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#. Harder to use, you need be more careful and logical while using pointers, miss using pointers might lead to the following: o Overwrite other variables. o Stack overflow. o Access areas of memory that doesn?t contain any data as they do. o Overwrite some information of the code for the .net runtime, which will surely lead your application to crash. Your code will be harder to debug. A simple mistake in using pointers might lead your application to crash randomly and unpredictably. Type-safety, using pointers will cause the code to fail in the .net type- safety checks, and of course if your security police don?t allow non type-safety code, then the .net framework will refuse to execute your application. Declaring Unsafe code in C# unsafe class Class1 { //you can use pointers here! } class Class1 { //pointer unsafe int * ptr; unsafe void MyMethod() { //you can use pointers here } } static void Main() { //can't use pointers here unsafe { //you can declare and use pointer here

2
} //can't use pointers here } Compiling UnSafe Code For compiling unsafe code use the /unsafe csc test.cs /unsafe In VS.net go to the project property page and in ?configuration properties>build? set Allow Unsafe Code Blocks to True. Declaring pointers int * ptri; double * ptrd; void *ptrVoid; Pointers to Structs and Class members Pointers can point to structs the same way we used before as long as they dont contain any reference types. The compiler will result an error if you had any pointer pointing to a struct containing a reference type. Classes and pointers is a different story. We already know that we cant have a pointer pointing to a class, where its a reference type for sure. The Garbage Collector doesnt keep any information about pointers, its only interested in references, so creating pointers to classes could cause the Garbage Collector to not work probably. On the other hand, class members could be value types, and its possible to create pointers to them. But this requires a special syntax. To create pointers pointing to class members by using fixed keyword: fixed (long *pX = &(myClass.X)) { // use *pX here only. } 2. What is managed code and managed data and managed Class? Managed Code : Managed code is code that is written to target the services of the Common Language Runtime In order to target these services, the code must provide a minimum level of information (metadata) to the runtime. All C#, Visual Basic .NET, and

3
JScript .NET code is managed by default. Visual Studio .NET C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/CLR). Managed Data : Closely related to managed code is managed datadata that is allocated and de-allocated by the Common Language Runtime's garbage collector. C#, Visual Basic, and JScript .NET data is managed by default. C# data can, however, be marked as unmanaged through the use of special keywords. Visual Studio .NET C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed Extensions for C++, a class can be marked as managed by using the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector. Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class. 3. Difference between managed and Unmanaged code Characteristic Coding model Identity Error handling mechanism Type compatibility Type definition Type safety Versioning Unmanaged model Interface-based GUIDs HRESULTs Binary standard Type library Not type safe Immutable Managed model Object-based Strong names Exceptions Type standard Metadata Optionally safe Resilient

Coding Model : Unmanaged objects always communicate through interfaces; managed objects and classes can pass data directly without implementing interfaces Error handling mechanisms COM methods usually return an HRESULT, indicating that the call succeeded or failed. Managed code incorporates exceptions. By default, COM interop maps managed exceptions to failure HRESULTs. Identities GUIDs identify a specific unmanaged type and provide no location information for that type. Strong names consist of a unique assembly name in addition to a type name. Because the assembly name uniquely identifies the type, you can reuse a type name across multiple assemblies. An assembly also introduces publisher key, version, and location information to a managed type. Interoperation services generate GUIDs and are strong-named as required. Type compatibility Types vary between managed and unmanaged code, and also among languages. Type definitions If you are accustomed to working with type libraries, you know that they contain only public types. Moreover, a type library is optional. In the managed programming model,

4
type information is mandatory for all types. Interoperation services provide tools that convert type libraries to metadata in assemblies and metadata to type libraries. Type safety Unmanaged compilers provide no type checking on pointer types, making the code susceptible to potentially harmful activity. In general, managed code requires a higher level of trust. Programmers can continue to use pointers in managed code, although the code has restrictions due to its unsafe behavior. Interoperation services prevent nontrusted, managed code from accessing unmanaged code. Versioning COM interfaces are immutable. If you change an interface, you must rename it with a new GUID. Managed types can evolve, keeping the same name. How to convert unmanaged codes to managed codes The static (Shared in Visual Basic) methods defined on the Marshal class are essential to working with unmanaged code. Marshalers who need to provide a bridge between the managed and unmanaged programming models uses this method. Name space : System.Runtime.InteropServices. What is Just-in-time Activation? Just-in-time (JIT) activation is a COM+ service that enables you to create an object as a non active, context-only object. The object remains non active until a client invokes a method on the object, at which point the runtime creates the full object. On the method call return, COM+ deactivates the object but leaves the context in memory. The deactivated object releases all resources, including locks on expensive data store. What is a JIT Compilation? Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Because the common language runtime supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be JIT-compiled and executed on computers with different architectures. At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe. What are the other ways of compiling a .Net Code to native code? The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. When using install-time code generation, the entire assembly that is being installed is converted into native code, taking into account what is known about other assemblies that are already installed. The resulting file loads and starts more quickly than it would have if it were being converted to native code by the standard JIT option. Can I look at the IL for an assembly? Yes. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly. Can source code be reverse-engineered from IL? Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL. How can I stop my code being reverse-engineered from IL? There is currently no simple way to stop code being reverse-engineered from IL. In future it is likely that IL obfuscation tools will become available, either from MS or from third parties. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult. Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL. Can I write IL programs directly? Yes.

4.

5.

6.

7.

8. 9. 10.

11.

5
Example .assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr "Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } } Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated. 12. Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays. 13. Diff between CLR & CTS 14. What is Type Safety (Memory)? As part of compiling MSIL to native code, code must pass a verification process. Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways. The runtime cannot prevent unsafe code from calling into native (unmanaged) code and performing malicious operations. When code is type safe, the runtime's security enforcement mechanism ensures that it does not access native code unless it has permission to do so Verification inspects code to determine whether the MSIL has been correctly generated because incorrect MSIL can lead to a violation of the type-safety rules. The verification process passes a well-defined set of type-safe code, and it passes only code that is type safe. However, some type-safe code might not pass verification due to limitations of the verification process, and some languages, by design, do not produce verifiably type-safe code. If type-safe code is required by security policy and the code does not pass verification, an exception is thrown when the code is executed. During the verification process, MSIL code is examined in an attempt to confirm that the code can access memory locations and call methods only through properly defined types. 15. Is it true that objects don't always get destroyed immediately when the last reference goes away? Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed. 16. Why doesn't the .NET runtime offer deterministic destruction? Because of the garbage collection algorithm. 17. Is the lack of deterministic destruction in .NET a problem? It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method?

6
Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this. 18. Does non-deterministic destruction affect the usage of COM objects from managed code? Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method. 19. I've heard that Finalize methods should be avoided. Should I implement Finalize on my class? An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources. Microsoft recommend the following pattern: public class CTest : IDisposable { public void Dispose() { ... // Cleanup activities GC.SuppressFinalize(this); } ~CTest() // C# syntax hiding the Finalize() method { Dispose(); } } In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach. Do I have any control over the garbage collection algorithm? A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect all unreferenced objects immediately. Can I avoid using the garbage collected heap? All languages that target the runtime allow you to allocate class objects from the garbagecollected heap. This brings benefits in terms of fast allocation, and avoids the need for programmers to work out when they should explicitly 'free' each object.The CLR also provides what are called ValueTypes -- these are like classes, except that ValueType objects are allocated on the runtime stack (rather than the heap), and therefore reclaimed automatically when your code exits the procedure in which they are defined. This is how "structs" in C# operate.Managed Extensions to C++ lets you choose where class objects are allocated. If declared as managed Classes, with the __gc keyword, then they are allocated from the garbage-collected heap. If they don't include the __gc keyword, they behave like regular C++ objects, allocated from the C++ heap, and freed explicitly with the "free" method. Will Gc remove the object from the managed heap at once the method is set to close or dispose Can the garbage collector(GC) can function on value type?

20. 21.

22. 23.

7
24. Methods to destroy explicitly Finalize() Dispose() (Ans) NClassName()

Potrebbero piacerti anche