Saturday, September 23, 2023
HomeApexDifference between with Sharing and without sharing keywords in Salesforce

Difference between with Sharing and without sharing keywords in Salesforce

When you use With Sharing keyword on a class, it will take into account the sharing rules of the current user. If we don’t use this keyword on a class, apex code will run in the system context.

Running the code in system context ensures that the code will not fail to run because of hidden fields or object restrictions. The only exception is in the case of executing an anonymous window. Execute anonymous will always run using full permissions of the current user.

How to use with Sharing keyword on a Class?

 public with sharing class HelloWorld { }

How to specify without sharing on a class?

When you use Without Sharing on a class, the sharing rules of the current user will not be enforced.

 public without sharing class SayHi { }

More about with Sharing and Without Sharing Keywords:

  • The sharing settings of the class in which the method is defined is applied,not of the class where the method is called.
    So if there is a method which is defined in a Class which has with sharing enabled but the method is called in a class which doesn’t have sharing(without sharing) enabled,the method will execute with sharing rules enforced.
  • We can declare inner and outer classes with sharing keyword. The sharing setting will be applied to all the code present in the class including intialization code, methods and constructors.
  • Inner classes do not inherit the sharing setting from the outer class.
    Classes inherit sharing setting from their parent class when one class extends from another class.

Let’s take a look at the below example:

In this example, we have declared a class with inherited sharing keyword. We have also created a visualforce page in order to call the apex code. Since we have used inherited sharing keyword with the class, only contacts for which the running user has access to will be displayed. If we remove the inherited sharing keyword in the class, in that case it will display all the contact records including the records which current user has no access to.

 public inherited sharing class ClassWithSharing { public List getAllTheUsers() { return [select name,id from contacts]; } }

Visualforce Page:

 <apex:page controller='ClassWithSharing'> <apex:repeat value='{!AllTheUsers}' var='record'> {!record.Name} </apex:page>

To learn more: with sharing and without sharing 



Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments