Tech Point Fundamentals

Friday, July 1, 2022

SQL Interview Questions and Answers - Part 06

SQL Interview Questions and Answers - Part 06

sql-interview-questions-answers

Are you preparing for the SQL Interview? If yes, then you are at the right place. This is the SQL Interview Questions and Answers article series. Here we will see Top 100+ SQL Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:




Please read the complete Design Pattern, C#, MVC, WebAPI, and .Net Framework Interview Questions and Answers article series here.




Introduction


This is the 6th part of the SQL Interview Questions and Answers article series. Each part contains eight to ten SQL Interview Questions with Answers. Please read all the SQL Interview Questions list here.

I will highly recommend to please read the previous parts over here before continuing the current part:





SQL Interview Questions and Answers - Part 06


Q42. What is the difference between CAST vs. CONVERT in SQL?

SQL Server supports both implicit and explicit conversions. Implicit conversions are those conversions that occur without specifying either the CAST or CONVERT function. 
Explicit conversions are those conversions that require the CAST or CONVERT function to be specified. 

Both CAST and CONVERT are functions used to convert one data type to another data type. In many instances, both CAST and CONVERT are used in combination and with each other to achieve certain effects in the data. Without using CAST or CONVERT functions, implicit conversions occur.

The first difference between CAST and CONVERT is CAST is an ANSI standard while CONVERT is a specific function in the SQL server.



The CONVERT function can be used for formatting purposes, especially for date/time, data type, and money/data type. But CAST is used to remove or reduce format while still converting.

So CAST can’t be used for Formatting Purposes. For example CAST('12/01/2016' AS DATE). But CONVERT can be used for Formatting Purposes by passing the appropriate style as a parameter. For example CONVERT(VARCHAR(20), GETDATE(), 101).

CAST is also a more portable function because the CAST function can be used by many databases. So CAST is also less powerful and less flexible than CONVERT. On the other hand, CONVERT allows more flexibility and is the preferred function to use for data, time values, traditional numbers, and money signifiers. CONVERT is also useful in formatting the data’s format.

CAST function is also used to restore the decimals and numerical values to integers while converting. It also can be used to truncate the decimal portion or value of an integer.




Q43. What does it mean to have QUOTED_IDENTIFIER ON in SQL?

  1. When SET QUOTED_IDENTIFIER is ON (default), identifiers can be delimited by double quotation marks (" "), and literals must be delimited by single quotation marks (' '). 
  2. All strings delimited by double quotation marks are interpreted as object identifiers. Therefore, quoted identifiers do not have to follow the Transact-SQL rules for identifiers.
  3. Double quotation marks cannot be used to delimit literal string expressions; single quotation marks must be used to enclose literal strings.
  4. SET QUOTED_IDENTIFIER must be ON when reserved keywords are used for object names in the database.
  5. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers.
  6. However, QUOTED_IDENTIFIER does not affect delimited identifiers enclosed in brackets ([ ]).
  7. SET QUOTED_IDENTIFIER must be ON when you are creating or changing indexes on computed columns or indexed views. If SET QUOTED_IDENTIFIER is OFF, then CREATE, UPDATE, INSERT, and DELETE statements will fail on tables with indexes on computed columns or tables with indexed views. 






Please watch the QUOTED_IDENTIFIER flag video here for the live demo.



Q44. What does it mean to have ANSI_NULL ON or OFF in SQL?

The ANSI_NULL Specifies ISO compliant behavior of the Equals (=) and Not Equal To (<>) comparison operators when they are used with null values in SQL Server.

ANSI_NULLS is one of seven SET options that must be set to required values when dealing with indexes on computed columns or indexed views. The options ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, QUOTED_IDENTIFIER, and CONCAT_NULL_YIELDS_NULL must also be set to ON, and NUMERIC_ROUNDABORT must be set to OFF.



When ANSI_NULLS is ON:

  1. When ANSI_NULLS is ON, all comparisons against a null value evaluate to UNKNOWN.
  2. A SELECT statement that uses WHERE column_name = NULL returns zero rows even if there are null values in column_name. 
  3. A SELECT statement that uses WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name.



When ANSI_NULLS is OFF:

  1. When SET ANSI_NULLS is OFF, comparisons of all data against a null value evaluate to TRUE if the data value is NULL.
  2. The Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard. 
  3. A SELECT statement that uses WHERE column_name = NULL returns the rows that have null values in column_name. 
  4. A SELECT statement that uses WHERE column_name <> NULL returns the rows that have nonnull values in the column.
  5. Also, a SELECT statement that uses WHERE column_name <> XYZ_value returns all rows that are not XYZ_value and that are not NULL.



SET ANSI_NULLS ON affects a comparison only if one of the operands of the comparison is either a variable that is NULL or a literal NULL. 

If SET ANSI_NULLS is not specified, the setting of the ANSI_NULLS option of the current database applies. ANSI_NULLS should be set to ON for executing distributed queries.

ANSI_NULLS must also be ON when you are creating or changing indexes on computed columns or indexed views. 

If SET ANSI_NULLS is OFF, any CREATE, UPDATE, INSERT, and DELETE statements on tables with indexes on computed columns or indexed views will fail.

Please watch the ANSI_NULLS  video here for a live demo.



Q45. What does it mean to have ANSI_PADDING ON or OFF in SQL?

ANSI_PADDING  controls the way the column stores values shorter than the defined size of the column, and the way the column stores values that have trailing blanks in char, varchar, binary, and varbinary data. 

The default for SET ANSI_PADDING is ON.  ANSI_PADDING should always be set to ON. When ANSI_DEFAULTS is ON, ANSI_PADDING is also enabled. ANSI_PADDING must be ON when you are creating or changing indexes on computed columns or indexed views. 

Columns defined with char, varchar, binary, and varbinary data types have a defined size. The ANSI_PADDING setting affects only the definition of new columns. After the column is created, SQL Server stores the values based on the setting when the column was created. Existing columns are not affected by a later change to this setting.








The SET ANSI_PADDING setting does not affect the nchar, nvarchar, ntext, text, image, varbinary(max), varchar(max), and nvarchar(max) data types. They always display the SET ANSI_PADDING ON behavior. This means trailing spaces and zeros are not trimmed.

When padded, char columns are padded with blanks, and binary columns are padded with zeros. When trimmed, char columns have the trailing blanks trimmed, and binary columns have the trailing zeros trimmed. The setting of ANSI_PADDING is defined at execute or run time and not at parse time.

Please watch the ANSI_PADDING set options video here for the live demo.



Q46. What is the difference between GO and Semicolon(;) Statement Terminator in SQL?

GO Terminator:

  1. The GO command was introduced by Microsoft tools as a way to separate batch statements such as the end of a stored procedure.
  2. The GO command is a client command and not a T-SQL server command. GO is not a SQL keyword.
  3. A "GO" is a batch separator and doesn`t actually even get sent to the server.
  4. SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server.
  5. Go is a Batch terminator. Go Signifies the end of a batch. The statements in the batch are compiled into a single execution plan. 
  6. The GO Statement must be written in a new line as it is not a T-SQL command i.e A Transact-SQL statement cannot occupy the same line as a GO command. 
  7. You cannot put a GO into a string of SQL (Dynamic SQL) and send it as part of the ADO.NET command object as SQL itself does not understand the term.


  8. GO can be used to invoke the same DML block multiple times using the following syntax: GO [count]
  9. Unlike semicolons, GO is mandatory before a new DDL.
  10. The command GO means the end of a batch, therefore all variables declared before GO are invalid after the GO command. Therefore the scope of local variables is limited to a batch, and cannot be referenced after a GO command.
  11. Any declarations of Variables, Table Variables, Temp Table, etc do not go across GO statements.
  12. You can not use a semicolon as a statement terminator after GO.
  13. You must have to use EXEC before the system stores procedures like sp_who if it is not the first statement in the batch.  
  14. All the CREATE statements must begin the batch. All other statements that follow in that batch will be interpreted as part of the definition of the first CREATE statement.
  15. So CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE TRIGGER, and CREATE VIEW statements cannot be combined with other statements in a batch.








Semicolon(;) Terminator:

  1. A semicolon is a statement terminator or statement separator. This is purely used to identify where a particular statement ends. 
  2. The semi-colon is used to signify the end of a statement itself, not necessarily a whole batch.
  3. Terminating SQL statements with semicolons was optional in SQL Server 2000 and in some cases actually not allowed.
  4. In SQL Server 2005, the introduction of Common Table Expressions (CTEs) and Service Broker Statements brought new formatting rules. It is used before a CTE Statement.
  5. Terminating a statement that preceded the Service Broker Statements (SEND, RECEIVE, BEGIN DIALOG CONVERSATION, and BEGIN CONVERSATION TIMER) and the CTEs (the WITH statement) became mandatory if those statements were not first in the batch.
  6. SQL Server 2008 introduced a new rule for terminating the MERGE statement with a semicolon. A MERGE statement must be terminated by a semi-colon.
  7. In SQL Server 2012 the THROW statement was introduced with the same rule for terminating the SQL statement as the WITH statement. If the THROW statement is not the first statement in the CATCH block the statement that precedes it must be terminated with the semicolon.
  8. This is noticeable in SQL scripts that need to return multiple recordsets, such as `select * from table1; select * from table2;` which would result in two separate recordsets on the client`s side.

Please watch the GO vs Semicolon statement terminator video here.



Q47. What is NULL in SQL? What is the difference between NULL and UNKNOWN?

ANSI-SQL defines NULL as a special value, or mark, that is used to indicate the absence of any data value. The ANSI-92 standard says that NULL in SQL is not a "data value", but rather an indicator that we have missing data. 

NULL is a special marker used in SQL to indicate that a data value does not exist in the database as of now but it may be present in the future when known. So, NULLs represent our "Known Unknowns".

The concept of NULL was Introduced by the creator of the relational database model i.e E. F. Codd in 1975. SQL Null serves to fulfill the requirement that all true relational database management systems (RDBMS) support a representation of "missing information and inapplicable information".

A NULL is not the same as a zero or empty string or a blank string. A SQL NULL is a state, not a value. 








You must use the IS NULL or IS NOT NULL operators to check for a NULL value.
It is not possible to test for NULL values with comparison operators, such as =, <, or <> when the ANSI NULL is set to OFF.

A NULL is not equal to other NULL. So every NULL is unique. You can not compare two NULL values. In fact, a NULL is not equal to anything. Comparisons with NULL always result in UNKNOWN.

Variables that have been declared, but not yet initialized via SET statement default to NULL. They are treated exactly like any other NULL values. 

If you perform scalar math operations and string concatenation functions with NULL, the result is always NULL. 

The LENGTH(NULL) will yield NULL but LENGTH('') would yield 0.

The COALESCE() function returns the first non-NULL value in its list of values.

Please watch the SQL NULL Value video here and the ISNULL vs COALESCE video here for more details.








Q48. What is SQL Three Valued Logic? How does it affect the application logic?

The Boolean or Binary logic has two values either true or false but three-valued logic has an additional value called “unknown”.  SQL uses a three-valued logic because besides true and false, the result of logical expressions can also be unknown.

SQL’s three-valued logic is a consequence of supporting NULL to mark absent data. The ternary logic involves when we try to compare NULLs to data values, or other NULLs. If a NULL value affects the result of a logical expression, the result is neither true nor false but unknown.



sql-3vl-logic



As per the ANSI-92 SQL Standard, comparisons with NULL always result in Unknown. NULL is equal to nothing, even NULL is not equal to NULL because each NULL could be different. So the ANSI-92 SQL Standard states that if one of the operands is NULL, the result of the comparison is "UNKNOWN".

Please watch the SQL Three Valued Logic video here for a live demo.








Q49. What is the difference between ISNULL() and COALESCE() function?

The COALESCE and ISNULL perform about the same in most cases in SQL Server. The ISNULL function has an important advantage over COALESCE in that internally it doesn`t evaluate an input expression more than once.

ISNULL is not the same as IS NULL (space between IS and NULL). IS NULL is an ANSI standard way to check for NULL value while ISNULL() is a function to replace the NULL value with an alternative value.

  1. The ISNULL() function is used to replace NULL with the specified replacement value. This function contains only two arguments. On the other hand, the Coalesce() function returns the first non-null value among its arguments. This function doesn't limit the number of arguments, but they must all be of the same data type.
  2. The COALESCE function is defined by the ANSI SQL standard and supported in all major databases. but ISNULL() is a T-SQL (Transact SQL) function and only works with Microsoft products e.g. Microsoft SQL Server.
  3. ISNULL is faster than COALESCE in SQL Server because of its built-in function implemented in the Database engine, while COALESCE translates to CASE statements.
  4. ISNULL() is a function while COALESCE is an expression in Microsoft SQL Server. Since ISNULL() is a function it is only evaluated once, but the input values for the COALESCE expression can be evaluated multiple times.







  5. The ISNULL() function contains only two parameters while the COALESCE() function contains multiple parameters. If we use more than two parameters with the ISNULL function then we must use nested ISNULL functions. 
  6. The COALESCE and ISNULL SQL Server statements handle data type precedence differently. COALESCE determines the type of the output based on data type precedence. While with ISNULL, the data type is not influenced by data type precedence, but rather by the first item in the list.
  7. The ISNULL() function looks at the first value and the second parameter value is automatically limited to that length but COALESCE() does not have this restriction.
  8. The ISNULL() function contains various types of parameters. The COALESCE() function doesn't limit the number of arguments, but they must all be of the same data type.
  9. Table columns created as the result of COALESCE are NULLable, while columns created as a result of ISNULL are not. The biggest impact you'll see from this difference is if you use a computed column and try to create a primary key or other non-null constraints on a computed column defined with COALESCE, you will receive an error.
  10. The COALESCE ignores the padding implicitly associated with concatenating a CHAR data type, while ISNULL obeys the specification for the first input and converts the empty string to a CHAR type size.
  11. An expression involving ISNULL with non-null parameters is considered to be NOT NULL, while expressions involving COALESCE with non-null parameters are considered to be NULL. 

Please watch the ISNULL vs COALESCE video here.


To Be Continued Part-07...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedInFacebookTelegramQuoraYouTubeTwitterPinterestTumbler, and VK for regular updates.

    

Sunday, June 26, 2022

C# Interview Questions and Answers - Part 06

C# Interview Questions and Answers - Part 06

csharp-interview-questions-and-answers-part1

Are you preparing for the C# Interview? If yes, then you are at the right place. This is the C# Interview Questions and Answers article series. Here we will see the top 150+ C# Interview Questions with Answers. 

Please visit our YouTube Channel for Interviews and other videos by below link:



Please read the complete Design Patterns Interview Questions and Answers series here.


Introduction


This is the 6th part of this C# Interview Questions and Answers article series. Each part contains 10 C# Interview Questions with Answers. Please read all the C# Interview Questions list here.

I will highly recommend you to please read the previous parts over here before continuing the current part:





C# Interview Questions and Answers - Part 06


Q051. What is the difference between value type and reference type?

In C#, the data types are categorized based on how they store their value in the memory. Considering this there are the following three types basically i.e value type, reference type, and pointer types.

A. Value Types:

  1. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type.
  2. All the value types are derived from System.ValueType and System.ValueType is derived from the ultimate super base class System.Object
  3. A value type data type holds a data value within its own memory space i.e value type variables contain directly values.


  4. A value type can be either an enum type or a structure type. All the primitive types are value types that are basically derived from an enum. For example - bool, int, char, enum, double, structure, etc.
  5. All the value types are stored in the stack. So a Value Type stores its contents in memory allocated on the stack.
  6. By default, on assignment, passing an argument to a method, and returning a method result, variable values are copied.
  7. Any operation on a value-type variable affects only that instance of the value type, stored in the variable.
  8. If a value type contains a data member of a reference type, only the reference to the instance of the reference type is copied when a value-type instance is copied. Both the copy and original value-type instance have access to the same reference-type instance.
  9. A value type variable cannot be null because it holds value, not a memory address. C# 2.0 introduced nullable types, using which you can assign null to a value type variable or declare a value type variable without assigning a value to it.
  10. A nullable value type T? represents all values of its underlying value type T and an additional null value. You cannot assign null to a variable of a value type unless it's a nullable value type.



B. Reference Types:

  1. On the other hand, Reference Types are used by a reference that holds a reference (address) to the object but not the object itself. 
  2. So a reference type doesn't store its value directly. Instead, it stores the address where the value is being stored.
  3. Since reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data.
  4. All the non-primitive data types are reference types. For example - string, class, delegate, array, and interface.
  5. The default value of a reference type variable is null when they are not initialized. Null means not referring to any object.
  6. All the reference types values are stored in the heap, but the variable is stored in the stack which points to the memory address of the referenced object. So when a reference type variable is no longer used, it can be marked for garbage collection.



C. Pointer Types:

  1. Generally, most of the C# code we write is "verifiably safe code", which means .NET tools can verify that the code is safe. 
  2. A safe code doesn't directly access memory using pointers. Instead, it creates managed objects directly. But C# also supports an unsafe context by pointers.
  3. A C# pointer is nothing but a variable that holds the memory address of another type. 
  4. But in C# pointer can only be declared to hold the memory address of value types and arrays. 
  5. Unlike reference types, pointer types are not tracked by the default garbage collection mechanism. That's why pointers are not allowed to point to a reference type or even to a structure type that contains a reference type. 
  6. So pointers can point to only unmanaged types which include all basic data types, enum types, other pointer types, and structs that contain only unmanaged types.



Q052. What is the difference between reference type and pass-by-reference?

Reference Types are the data types that hold a reference (address) to the object. They are stored in the heap. 

Since reference types represent the address of the variable rather than the data itself, assigning a reference variable to another doesn't copy the data. On the other hand, pass-by-reference is a way to pass a value type object or variable as a reference to a method as a parameter.

When you pass a reference type variable from one method to another, it doesn't create a new copy; instead, it passes the variable's address. So, if we change the value of a variable in a method, it will also be reflected in the calling method.

In c#, passing a value type parameter to a method by reference means passing a reference of the variable to the method. So the changes made to the parameter inside the called method will affect the original data stored in the argument variable.



We use OUT and REF keywords to pass a value type as a reference type in C#. Don't confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same.

A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference. 
If you pass a reference type object (class object) as a parameter, it sends the address, not the actual data which is referenced by the reference type object.

Please watch the Reference Type vs Pass By Reference video here.

Now anyone can get confused about string because it does not follow the above rule. Actually, a string is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. 

If we change a string value, then the compiler creates a new string object in the memory and points that variable to the new memory location. So, passing a string value to a function will create a new variable in the memory, and any change in the value in the function will not be reflected in the original value. 

Please watch the String vs StringBuilder video here for more details.




Q053. What is the difference between OUT and REF type parameters?

In C# both REF and OUT are known as reference parameters that are used for passing an argument by reference. Properties are not variables, therefore it cannot be passed as an out or ref parameter.

Both REF and OUT are treated differently at run time but they are treated the same at compile time. So two methods cannot be overloaded if one method takes an argument as REF and the other takes an argument as an OUT. 






REF Parameter:

  1. A method parameter can be modified by REF regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.
  2. An argument that is passed to a REF parameter must be initialized before it is passed.
  3. To use a REF parameter, both the method definition and the calling method must explicitly use the REF keyword.
  4. REF is used to state that the parameter passed may be modified by the method. So the REF parameter may or may not be modified by the called method.



OUT Parameter:

  1. Variables passed as OUT arguments do not have to be initialized before being passed in a method call. 
  2. The OUT is used to state that the parameter passed must be modified by the called method. So the called method is required to assign a value before the method returns.
  3. To use an OUT parameter, both the method definition and the calling method must explicitly use the OUT keyword. 
  4. The OUT keyword can also be used with a generic type parameter to specify that the type parameter is covariant.

Please read the method overloading rules for REF vs OUT here for more details. 



REF vs OUT Parameter:

Following are the most common difference between REF vs OUT:

  1. The REF parameter must be initialized before it is passed to the ref parameter. But it is not mandatory for the OUT parameter.
  2. In the called method, it is mandatory to initialize the OUT parameters before using or returning to the calling method. But it is not mandatory for REF parameters.
  3. A REF type parameter is bi-directional i.e it can be used to pass a value and get the updated value from the called method. But OUT parameter is uni-directional i.e it can only be used to get the value from the called method.

Please watch the OUT vs REF video here.




Q054. Can you pass a constant as a reference? Why?

No, a constant variable can not be passed as a reference in C#. There are below justification for that:

Constants are something that is used for holding a value that can not be changed during the program or app domain.

Constants are compile-time constants, so they must be set along with the declaration itself.
By default, all the const types are static internally.

Please watch the Const vs Readonly video here.









Q055. If a method's return type is void, can you use a return statement in the method? What is the use of the return keyword?

Yes, we can use the return keyword but without any value. 

A void function performs a task, and then control returns back to the caller but it does not return a value. 

You can use the return statement, as there is no return value. Even without the return statement, control will return to the caller automatically at the end of the function.




Q056. What is a recursive method? Can you tell me any available recursive method names in C#?

In C# there is no difference between function and method except that functions are not utilizable outside of their classes usually because they are declared as private. In C# we had only methods but the anonymous function has been added to C#, since .NET Framework 3.5.

A recursive function is a function that calls itself. A function that calls another function is normal and used in daily programming but when a function calls itself then it is a recursive function.

A recursive algorithm is a special type of algorithm in which a method calls itself over and over again to solve a problem. Each successive call reduces the complexity of the problem and moves closer and closer to a solution until finally a solution is reached, the recursion stops, and the method can exit.  

Recursive algorithms are fairly easy to identify because the method name appears in the method body. Recursive algorithms are about breaking complex problems down into smaller more manageable problems.

Real Examples of Recursion:

  1. Binary Search
  2. Tower of Hanoi Problem
  3. Fibonacci Numbers
  4. Factorial Numbers
  5. Merge Sort
  6. Directory and file Search



Q057. In C# strings are the value type or reference type? How?

In C# strings are reference types but behave like value types.  Actually, a string is a reference type, but it is immutable. It means once we assigned a value, it cannot be changed. 

If we change a string value, then the compiler creates a new string object in the memory and points that variable to the new memory location. 






So, passing a string value to a function will create a new variable in the memory, and any change in the value in the function will not be reflected in the original value. 

Please watch the String vs StringBuilder video here for more details.




Q058. Enums are value type or a reference type in C#? 

In C# enums are value type. An enumeration type is a value type defined by a set of named constants of the underlying integral numeric type. By default, the associated constant values of enum members are of type int; they start with zero and increase by one following the definition text order. 

The System.Enum type is the abstract base class of all enumeration types in C#. It provides a number of methods to get information about an enumeration type and its values

You cannot define a method inside the definition of an enumeration type. To add functionality to an enumeration type, create an extension method.



Q059. In C#, the structure is a value type or a reference type?

Structures are value types in C#. A structure or struct is a simple user-defined type and lightweight alternative to a class.  A struct is simply a composite data type consisting of any number of other types. 

In C# all struct types are implicitly inherited from System.ValueType which, in turn, inherits from the System.Object class, so, it is possible to override the methods of the Object class inside a struct by using the keyword override. Remember that this is a special case in C# structs. 



Structure Fundamental Points:

  1. In C# structs are value types. The default modifier is internal for the struct and its members.
  2. A structure can contain only a parameterized constructor or a static constructor.
  3. Like a class, a structure can also contain constants, fields, methods, properties, indexers, operators, events, and nested types. A struct can also contain static members, but a static member of the struct type is referenced.
  4. A struct can also be passed by reference to a method using a REF or OUT parameter. Boxing and Unboxing are used internally to convert between a struct type and object.
  5. A struct does not support inheritance, but it can implement interfaces. So a struct cannot inherit from any struct or class.


  6. The accessibility of a struct member cannot be protected or protected internal because inheritance is not supported for structs.
  7. A struct member cannot be specified as abstract, sealed, virtual. But a struct can be partial.
  8. A struct cannot contain any explicit default constructor i.e parameterless constructor because every struct implicitly has a parameterless instance constructor that always sets the default value to its member fields.
  9. Parameterized constructors are allowed but destructors or finalizers are not allowed in any structure.
  10. A structure can never be abstract because all the structures are implicitly sealed. So abstract and sealed modifiers are not allowed in a struct declaration.
  11. Instance field member declarations for a struct are not permitted to include variable initializers. But static fields of a struct are permitted to include variable initializers.
  12. It is not possible for the value of a struct type to be null because structs are not referenced types.

Please read the complete C# Structure article here




Q060. What is the difference between casting and conversion in C#?

Since C# is statically-typed at compile-time, after a variable is declared, it cannot be declared again or assigned a value of another type unless that type is implicitly convertible to the variable's type. 

However, you might sometimes need to copy a value into a variable or method parameter of another type. To achieve that there are two different ways in C# i.e Casting and Conversion.

The main difference between type conversion and typecasting is that type conversion is done “automatically” by the compiler whereas, typecasting is done “explicitly" by the programmer.






1. Conversion: An implicit conversion in C# is known as conversion. The compiler does it internally. No special syntax is required because the conversion always succeeds and no data will be lost. The conversion includes conversions from smaller to larger integral types, and conversions from derived classes to base classes.



2. Casting: An explicit conversion in C# is known as casting. This explicit conversion requires a cast expression known as cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. For example numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.

Apart from this, there are some inbuilt helper classes as well in the .Net framework for doing the explicit conversion for example System.Convert class and Int32.Parse etc. Please watch the Conversion vs Casting video here.

Boxing and Unboxing are not the same as conversion and casting. Please watch the boxing vs unboxing video here for more details.









To Be Continued Part-07...


Recommended Articles






Thanks for visiting this page. Please follow and join us on LinkedIn, Facebook, Telegram, Quora, YouTube, Twitter, Pinterest, Tumbler, and VK for regular updates.