- Structs may seem similar to classes
- Members of a class are private by default and members of struct are public by default.
- When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private.
- Structures can’t have modifiers like abstract, sealed, and static whereas classes can have.
- Both structure and class can have partial modifiers.
- A structure couldn't have a destructor but in class it is possible.
- Classes can be inherited whereas structures not. By default structures are sealed, that is the reason structures are not supporting inheritance.
- You will always be dealing with instance of a class. But you can’t deal with instance of a struct (but dealing directly with them).
- Field/Member can't be instantiated within structures but classes allow as in the following:
struct myStructure
{
string x = 2;//Not allowed
}
class myClass
{
string x = 2;//Allowed
} - Process of converting structure type into object type is called boxing and process of converting object type into structure type is called unboxing.
Ex: int a=10;
Object ob = (object) a; //Boxing
a= (int) obj; //Unboxing - Classes are Reference types (When you instantiate a class, it will be allocated on the heap) and Structures are Values types (lives on stack). So a class variable can be assigned null. But we cannot assign null to a struct variable.
Static Public void Main (string [] arg) {MyClass obj1 =new MyClass ();
obj1.DataMember=10;
MyClass obj2 =obj1;
obj2.DataMember=20;
}
In the above program, “MyClass obj2 =obj1” instruction indicates that both variables of type MyClass obj1 and obj2 will point to the same memory location. It basically assigns the same memory location into another variable of same type.
So if any changes that we make in any one of the objects type MyClass will have an effect on another since both are pointing to the same memory location.
“obj1.DataMember=10” at this line both the object’s data members will contain the value of 10. obj2.DataMember=20 at this line both the object’s data member will contains the value of 20. Eventually, we are accessing datamembers of an object through pointers.
Unlike classes, structures are value types. For example:
Structure MyStructure {Public Int DataMember; //By default, accessibility of Structure data
//members will be private. So I am making it as
//Public which can be accessed out side of the structure.
}
Static Public void Main (string [] arg){MyStructure obj1 =new MyStructure ();
obj1.DataMember=10;
MyStructure obj2 =obj1;
obj2.DataMember=20;
}
In the above program, instantiating the object of MyStructure type using new operator and storing address into obj variable of type MyStructure and assigning value 10 to data member of the structure using “obj1.DataMember=10”. In the next line, I am declaring another variable obj2 of type MyStructure and assigning obj1 into that. Here .NET C# compiler creates another copy of obj1 and assigns that memory location into obj2.
So whatever change we make on obj1 will never have an effect on another variable obj2 of type MyStructrue. So that’s why we are saying Structures are value types. - All struct types implicitly inherit from the class System.ValueType
- In general, classes can be used when you have more complex data. And if you think that these data to be modified after creating an instance of class, then classes are absolute methods.
- Structs can be used for small data structures. If developer feels that data members of structure cannot be modified after creating structure, then having structure will suit.
- The “this” keyword gives different meaning in structure and class. How?
In class, “this” keyword is classified as value type of class.
In structure, “this” keyword is classified as variable type of structure. - Structure must always have the default parameter-less constructor defined as public but a class might have one, so you can't define a private parameter-less constructor in structure as in the following:
struct Me
{ private Me()// compile-time error
{ } }class Me
{ private Me()// runs Ok
{ } } - A structure can't be abstract, a class can.
- Structure can inherit from interface not from any class or from other structure
Blog that contains articles about new technologies related or not with programming. I will describe and solves some problems that I encounter in my career. ASP .NET, AJAX, Javascript, C++, C# and SQL are some of the subjects that will appear.
07 August 2015
Struct Vs Class in C#
21 May 2015
Sql Query vs Linq to Sql Query VS Entity Query
select NAME as names from dbo.MASTER where NAME like '%value%'
IList<string> names = (from OM in dbo.MASTER where OM.NAME.Contains("value") select OM.NAME).ToList<string>();
IList<string> names = dbo.MASTER.Where(x => x.NAME.Contains("value")).Select(x => x.NAME).ToList<string>();
Left vs right join in linq to sql
var results = from tbl1 in table1
join tbl2 in table2
on tbl1.User equals tbl2.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = tbl1,
UserGrowth = j
};
If you want to do a right join, just swap the tables that you're selecting, like so:
var results = from tbl2 in table2
join tbl1 in table1
on tbl2.User equals tbl1.User into joined
from j in joined.DefaultIfEmpty()
select new
{
UserData = j,
UserGrowth = tbl2
};
The important part of the code is the into statement, followed by the DefaultIfEmpty. This tells Linq that we want to have the default value (i.e. null) if there isn't a matching result in the other table.
A right outer join is not possible with LINQ. LINQ only supports left outer joins. If we swap the tables and do a left outer join then we can get the behavior of a right outer join.
19 May 2015
orderby in linq to sql
from M in dbo.MASTER
where M.UNIVERSE != null orderby M.UNIVERSE
select new { M.UNIVERSE } ).Distinct();
12 May 2015
Difference between substring and substr in JavaScript
substring takes parameters as (from, to).
alert("abc".substr(1,2)); // returns "bc"
alert("abc".substring(1,2)); // returns "b"
11 May 2015
Clustered & Non-Clustered Indexes in SqlServer
Suppose we have 16 million records. When we try to retrieve records for two or three customers based on their customer id, all 16 million records are taken and comparison is made to get a match on the supplied customer ids. Think about how much time that will take if it is a web application and there are 25 to 30 customers that want to access their data through internet. Does the database server do 16 million x 30 searches? The answer is no because all modern databases use the concept of index.
Index is a database object, which can be created on one or more columns (16 Max column combinations). When creating the index will read the column(s) and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some overhead on data modification such as create, delete and modify.
If a table has a clustered index, then the rows of that table will be stored on disk in the same exact order. All the same entries belonging of a table would be right next to each other on disk. This is the “clustering”, or grouping of similar values, which is referred to in the term “clustered” index the query will run much faster than if the rows were being stored in some random order on the disk.
Drawback with Clustered Index:
If a given row has a value updated in one of its (clustered) indexed columns what typically happens is that the database will have to move the entire row so that the table will continue to be sorted in the same order as the clustered index column. Clearly, this is a performance hit. This means that a simple UPDATE has turned into a DELETE and then an INSERT – just to maintain the order of the clustered index. For this exact reason, clustered indexes are usually created on primary keys or foreign keys, because of the fact that those values are less likely to change once they are already a part of a table.
A table can have up to 999 non-clustered indexes because they don’t affect the order in which the rows are stored on disk like clustered indexes.
Clustered index defines the way in which data is ordered physically on the disk. And there can only be one way in which you can order the data physically. Imagine if we have two clustered indexes on a single table – which index would determine the order in which the rows will be stored? Since the rows of a table can only be sorted in only one way/index, a non-clustered index has no effect on which the order of the rows will be stored. So having more than one clustered index is not allowed.
A comparison of a non-clustered index with a clustered index with an example:
Non clustered indexes store both a value and a pointer to the actual row that holds that value. Clustered indexes don’t need to store a pointer to the actual row because of the fact that the rows in the table are stored on disk in the same exact order as the clustered index – and the row-level data like EmployeeName, EmployeeAddress, etc. are stored in its leaf nodes of the clustered index. This means that with a non-clustered index, extra work is required to retrieve data, as compared to clustered index. So, reading from a clustered index is generally faster than reading from a non-clustered index.
SQL server is using the Binary-Tree techniques to represent the clustered index. The Index page in a book is Non-Clustered index and the page numbers are clustered index arranged in a binary tree.
CREATE INDEX index_name ON table_name (column_name)
CREATE UNIQUE CLUSTERED INDEX index_name ON dbo.[Package](CreateDateKey, PackageID) WITH (ONLINE = ON, DATA_COMPRESSION = ROW)
ALTER TABLE dbo.Package WITH CHECK
ADD CONSTRAINT [index_name] PRIMARY KEY (PackageID) ON [PRIMARY]
ALTER TABLE dbo.Package WITH CHECK ADD CONSTRAINT [index_name] PRIMARY KEY NONCLUSTERED (PackageID) ON [PRIMARY]
DROP INDEX table_name.index_name
06 May 2015
Serialization vs DeSerialization
Serialization is the process of converting an object into some data format such as XML or stream of bytes in order to store the object to a memory, or a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.
You can serialize an object and transport it over the internet using HTTP between a client and a server. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format for storage or transport.
Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
System.XML.Serialization/System.Runtime.Serialization contains the classes necessary for serializing and deserializing objects into XML format and Binary format respectively
Binary format serialization is faster than XML serialization, because Binary format writes the raw data but XML format serialization needs formatting of data as per XML
In Binary format serialization all members will be serialized.
- XML serialization only serializes pubic fields and properties
- XML serialization does not include any type information
- We need to have a default/non-parameterized constructor in order to serialize an object
- ReadOnly properties are not serialized
Let's start with a basic example. Here is a simple class the need to be serialized :
public class AddressDetails
{
public int HouseNo { get; set; }
public string StreetName { get; set; }
public string City { get; set; }
private string PoAddress { get; set; }
}
Code to serialize the above class:
using System.Xml.Serialization;
using System.IO;
public static void Main(string[] args)
{
AddressDetails details = new AddressDetails();
details.HouseNo = 4;
details.StreetName = "Rohini";
details.City = "Delhi";
Serialize(details);
}
static public void Serialize(AddressDetails details)
{
XmlSerializer serializer = new XmlSerializer(typeof(AddressDetails));
using (TextWriter writer = new StreamWriter(@"C:\Xml.xml"))
{
serializer.Serialize(writer, details);
}
}
The output after the serialization is :
<?xml version="1.0" encoding="utf-8"?>
<AddressDetails>
<HouseNo>4</HouseNo>
<StreetName>Rohini</StreetName>
<City>Delhi</City>
</AddressDetails>
Serialization can be of the following types:
- Binary Serialization
- SOAP Serialization
- XML Serialization
If the server and client application are .NET applications, the user can make use of binary serialization. If the client and server use two different types of systems, then the user can make use of XML type serialization. XML serialization is useful when user wants full control of how the property can be serialized. It supports XSD standard.
Remoting and Web Services depend heavily on Serialization and De-serialization.
XML Serialization Attributes
XmlAttribute: This member will be serialized as an XML attribute
XmlElement: The field will be serialized as an XML element, ex: [XmlElement("Number")]
XmlIgnore: Field will be ignored while Serialization
XmlRoot: Represent XML document's root Element
05 May 2015
Create a new object in JavaScript
22 January 2015
IEnumerable vs IQueriable
IEnumerable:
-IEnumerable exists in System.Collections Namespace.
-IEnumerable can move forward only over a collection, it can’t move backward and between the items.
-IEnumerable is best to query data from in-memory collections like List, Array etc.
-While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.
-IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
-IEnumerable supports deferred execution.
-IEnumerable doesn’t supports custom query.
-IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
-Extension methods supports by IEnumerable takes functional objects.
IEnumerable Example:
MyDataContext dc = new MyDataContext ();
IEnumerable list = dc.Employees.Where(p => p.Name.StartsWith("S"));
list = list.Take(10);
Generated SQL statements of above query will be:
SELECT EmpID, EmpName, Salary FROM Employee WHERE EmpName LIKE '%S%'
Notice that in this query "top 10" is missing since IEnumerable filters records on client side
IQueryable:
-IQueryable exists in System.Linq Namespace.
-IQueryable can move forward only over a collection, it can’t move backward and between the items.
-IQueryable is best to query data from out-memory (like remote database, service) collections.
-While query data from database, IQueryable execute select query on server side with all filters.
-IQueryable is suitable for LINQ to SQL queries.
-IQueryable supports deferred execution.
-IQueryable supports custom query using CreateQuery and Execute methods.
-IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
-Extension methods supports by IQueryable takes expression objects means expression tree.
IQueryable Example:
MyDataContext dc = new MyDataContext ();
IQueryable list = dc.Employees.Where(p =>p.Name.StartsWith("S"));
list = list.Take(10);
Generated SQL statements of above query will be :
SELECT TOP 10 EmpID, EmpName, Salary FROM Employee WHERE EmpName LIKE '%S%'
Notice that in this query "top 10" is exist since IQueryable executes query in SQL server with all filters.
Extending using Extension methods
this
keyword . Let define one more function in int
called Multiply
to see this in action.static class MyExtensionMethods
{
public static int Multiply(this int val, int multiplier)
{
return val * multiplier; //10*2
}
}
static void Main(string[] args)
{
// Passing arguments in extension methods
int i = 10;
Console.WriteLine(i.Multiply(2).ToString());
}
Why only one Clustered Index per table?
- Clustered index defines the way in which data is ordered physically on the disk. And there can only be one way in which you can order the data physically.
- Imagine if we have two clustered indexes on a single table – which index would determine the order in which the rows will be stored?
- Since the rows of a table can only be sorted to follow just one index, having more than one clustered index is not allowed.
09 July 2014
Abstract Class
In dynamic polymorphism (over riding) the object of class reused with polymorphism method which has called only in the runtime. The decision about function execution is made at run time. Method overloading, method overriding, hiding comes under this approach.
The mechanism of linking a function with an object at run time is called dynamic or late binding.
C# uses two approaches to implement dynamic polymorphism,
- Abstract Classes
- Virtual Function
A class can be consumed from other classes in two different approaches,
- Inheritance (Inherit & Consume).
- By creating the object and consume.
Abstract class: The class under which we declared abstract methods is known as abstract class and should be declared with abstract modifier.
An abstract class can contain abstract members as well as non-abstract members.
A Method without any method body is known as an Abstract method. It contains only the declaration of the method, it should be declared by using the abstract modifier. This incomplete (abstract methods) must be implemented in a derived class.
An abstract class cannot be instantiated directly. An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited. If it is so, it is useless.
An abstract method is implicitly a virtual method. This is accomplished by adding the keyword abstract before the return type of the method. An abstract member cannot be static.
The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
Use abstract classes when you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes. As it simplifies versioning, this is the practice used by the Microsoft team which developed the Base Class Library. (COM was designed around interfaces.)
So, abstract class defines a common base class for a family of types with a default behavior
For e.g. Again take the example of the Vehicle class above. If we want all classes deriving from Vehicle to implement the Drive() method in a fixed way whereas the other methods can be overridden by child classes. In such a scenario we implement the Vehicle class as an abstract class with an implementation of Drive while leave the other methods/ properties as abstract so they could be overridden by child classes.
An Abstract class can
- Had instance variables (like constants and fields), constructors and destructor.
- Can inherit from another abstract class or another interface.
An Abstract class cannot
- Inherited by structures.
- Support multiple inheritances.
- The concept of abstract method is nearly related with the concept of method overriding. Where in overriding parent class declared a method as virtual and child class re-implements that method by using the override keyword.
- In case of abstract method parent class method is abstract which has to be implemented by the child class by using the override keyword only.
- The method overriding re-implemented/overriding the method is optional in virtual methods. Where as in abstract methods implementing/overriding the method is mandatory.
04 July 2014
Difference between Response.Redirect() and Server.Transfer()
Response.Redirect() is used to navigate the user request between multiple webservers
whereas Server.Transfer() is used to navigate the user request within the webserver.
Response.Redirect() will not hide the Destination url address.
Server.Transfer() will hide the destination url address
Viewstate and hiddenfields data is collapsed in both cases of redirect or transfer
If you are using Server.Transfer then you can directly access the values, controls and properties of the previous page which you can’t do with Response.Redirect, Instead you can use querystrings
Server.Transfer sends a request directly to the web server and the web server delivers the response to the browser. So it is faster since there is one less roundtrip. but again it all depends on your requirement.
Response.Redirect can be used for both .aspx and HTML pages whereas Server.Transfer can be used only for .aspx pages and is specific to ASP and ASP.NET.
Both Response.Redirect and Server.Transfer have the same syntax like:
Response.Redirect("login.aspx");
Server.Transfer("login.aspx");
Logic for two tables mismatched columns
insert into staging
select 100,'hyderbad,india' union all
select 101,'banglore,india' union all
select 102,'banglore,india'
create table oltp (client_id int primary key,address_details varchar(250));
insert into oltp
select 104,'newyork,usa' union all
select 105,'chicago,usa' union all
select 106,'washington,usa'
select * from oltp where client_id in (select client_id from staging)
o/p:
It returns all 2nd table rows.. instead of raising error that column-name is not existing in table
It will fetch all the values from outer query as inner query referring the same column from outer query .If a column is referenced in a subquery that does not exist in the table referenced by the subquery's FROM clause, but exists in a table referenced by the outer query's FROM clause, the query executes without error. SQL Server implicitly qualifies the column in the subquery with the table name in the outer query.
With ties clause in sqlserver
FROM (
SELECT 1 COL UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 4 UNION ALL
SELECT 3 UNION ALL
SELECT 4
) A
ORDER BY COL
Answer: | 1,2,3,3,4,4,4 |
Explanation: | Using TOP with "WITH TIES" give all matching values with the last TOP (n) rows in ORDER BY columns. In simple way, if you will specify top 3 then it will give result 1,2,3,3 as there are two same value in that column.For top 5, it will give the result as 1,2,3,3,4,4,4 because top 5th value is 4. It will find same value in the column used in ORDER BY until the last row of the table.That's why top 6 returned 1,2,3,3,4,4,4 as top 6th is 4 so it will look for value 4 in entire COL column values. If matches are found, then it will include all those as well.Refs: http://msdn.microsoft.com/en-IN/library/ms189463(v=sql.90).aspx |